portkey-admin-mcp 0.16.4 → 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) {
@@ -1582,9 +1649,10 @@ var McpIntegrationsService = class extends BaseService {
1582
1649
  `/mcp-integrations/${this.encodePathSegment(id)}/metadata`
1583
1650
  );
1584
1651
  }
1585
- async listMcpIntegrationCapabilities(id) {
1652
+ async listMcpIntegrationCapabilities(id, params) {
1586
1653
  return this.get(
1587
- `/mcp-integrations/${this.encodePathSegment(id)}/capabilities`
1654
+ `/mcp-integrations/${this.encodePathSegment(id)}/capabilities`,
1655
+ { type: params?.type }
1588
1656
  );
1589
1657
  }
1590
1658
  async updateMcpIntegrationCapabilities(id, data) {
@@ -1628,6 +1696,8 @@ var McpServersService = class extends BaseService {
1628
1696
  current_page: params?.current_page,
1629
1697
  page_size: params?.page_size,
1630
1698
  workspace_id: params?.workspace_id,
1699
+ id: params?.id,
1700
+ search: params?.search,
1631
1701
  tags: params?.tags === void 0 ? void 0 : JSON.stringify(params.tags)
1632
1702
  });
1633
1703
  }
@@ -1656,7 +1726,8 @@ var McpServersService = class extends BaseService {
1656
1726
  `/mcp-servers/${this.encodePathSegment(id)}/capabilities`,
1657
1727
  {
1658
1728
  current_page: params?.current_page,
1659
- page_size: params?.page_size
1729
+ page_size: params?.page_size,
1730
+ type: params?.type
1660
1731
  }
1661
1732
  );
1662
1733
  }
@@ -1672,7 +1743,8 @@ var McpServersService = class extends BaseService {
1672
1743
  `/mcp-servers/${this.encodePathSegment(id)}/user-access`,
1673
1744
  {
1674
1745
  current_page: params?.current_page,
1675
- page_size: params?.page_size
1746
+ page_size: params?.page_size,
1747
+ search: params?.search
1676
1748
  }
1677
1749
  );
1678
1750
  }
@@ -1771,6 +1843,8 @@ var PromptsService = class extends BaseService {
1771
1843
  string: raw.string ?? "",
1772
1844
  parameters: raw.parameters ?? {},
1773
1845
  model: raw.model,
1846
+ ai_model_id: raw.ai_model_id,
1847
+ finetune_id: raw.finetune_id,
1774
1848
  virtual_key: raw.virtual_key,
1775
1849
  functions: raw.functions ?? void 0,
1776
1850
  tools: raw.tools ?? void 0,
@@ -1782,12 +1856,14 @@ var PromptsService = class extends BaseService {
1782
1856
  object: "prompt"
1783
1857
  };
1784
1858
  }
1785
- async updatePrompt(promptId, data) {
1859
+ async updatePrompt(promptId, data, options = {}) {
1786
1860
  const { template_metadata, is_raw_template, ...rest } = data;
1787
1861
  const body = {
1788
1862
  ...rest,
1789
- // Enable partial updates so missing version fields are backfilled from latest version
1790
- 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
1791
1867
  };
1792
1868
  if (template_metadata !== void 0) {
1793
1869
  body.prompt_metadata = template_metadata;
@@ -2014,24 +2090,42 @@ var PromptsService = class extends BaseService {
2014
2090
  data.target_collection_id
2015
2091
  );
2016
2092
  if (existingTarget) {
2017
- const updateResult = await this.updatePrompt(existingTarget.id, {
2018
- string: sourceVersion.string,
2019
- parameters: sourceVersion.parameters,
2020
- model: sourceVersion.model,
2021
- virtual_key: data.virtual_key || sourceVersion.virtual_key,
2022
- functions: sourceVersion.functions,
2023
- tools: sourceVersion.tools,
2024
- tool_choice: sourceVersion.tool_choice,
2025
- is_raw_template: sourceVersion.is_raw_template,
2026
- version_description: `Promoted from ${sourcePrompt.slug} v${sourceVersion.version_number}`,
2027
- template_metadata: {
2028
- ...sourceVersion.template_metadata,
2029
- env: data.target_env,
2030
- promoted_from: sourcePrompt.slug,
2031
- promoted_from_version: sourceVersion.version_number.toString(),
2032
- promoted_at: (/* @__PURE__ */ new Date()).toISOString()
2033
- }
2034
- });
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
+ );
2035
2129
  return {
2036
2130
  source_prompt_id: data.source_prompt_id,
2037
2131
  source_version_id: sourceVersion.id,
@@ -2115,12 +2209,17 @@ var ProvidersService = class extends BaseService {
2115
2209
  });
2116
2210
  }
2117
2211
  async updateProvider(slug, data, workspaceId) {
2118
- const path = workspaceId ? `/providers/${this.encodePathSegment(slug)}?workspace_id=${encodeURIComponent(workspaceId)}` : `/providers/${this.encodePathSegment(slug)}`;
2119
- return this.put(path, data);
2212
+ return this.put(
2213
+ `/providers/${this.encodePathSegment(slug)}`,
2214
+ data,
2215
+ { workspace_id: workspaceId || void 0 }
2216
+ );
2120
2217
  }
2121
2218
  async deleteProvider(slug, workspaceId) {
2122
- const path = workspaceId ? `/providers/${this.encodePathSegment(slug)}?workspace_id=${encodeURIComponent(workspaceId)}` : `/providers/${this.encodePathSegment(slug)}`;
2123
- const result = await this.delete(path);
2219
+ const result = await this.delete(
2220
+ `/providers/${this.encodePathSegment(slug)}`,
2221
+ { workspace_id: workspaceId || void 0 }
2222
+ );
2124
2223
  return isNoContent(result) ? {} : result;
2125
2224
  }
2126
2225
  };
@@ -2347,7 +2446,7 @@ function getSharedServiceCacheKey(apiKey) {
2347
2446
  const keyDigest = createHmac("sha256", SERVICE_CACHE_HMAC_KEY).update(apiKey).digest("hex");
2348
2447
  return JSON.stringify({
2349
2448
  apiKey: keyDigest,
2350
- baseUrl: process.env.PORTKEY_BASE_URL?.trim() || ""
2449
+ baseUrl: process.env.PORTKEY_BASE_URL ?? DEFAULT_BASE_URL
2351
2450
  });
2352
2451
  }
2353
2452
  var sharedPortkeyServices = /* @__PURE__ */ new Map();
@@ -2377,8 +2476,7 @@ var PortkeyService = class {
2377
2476
  health;
2378
2477
  constructor(apiKey) {
2379
2478
  const resolvedApiKey = resolvePortkeyApiKey(apiKey);
2380
- const resolvedBaseUrl = process.env.PORTKEY_BASE_URL ?? "https://api.portkey.ai/v1";
2381
- validateUrl(resolvedBaseUrl);
2479
+ const resolvedBaseUrl = process.env.PORTKEY_BASE_URL ?? DEFAULT_BASE_URL;
2382
2480
  this.accessPolicies = new AccessPoliciesService(
2383
2481
  resolvedApiKey,
2384
2482
  resolvedBaseUrl
@@ -2452,8 +2550,8 @@ var SecretReferenceListItemSchema = z3.object({
2452
2550
  slug: z3.string(),
2453
2551
  manager_type: SecretManagerTypeSchema,
2454
2552
  status: z3.literal("ACTIVE"),
2455
- created_at: z3.iso.datetime(),
2456
- last_updated_at: z3.iso.datetime(),
2553
+ created_at: z3.iso.datetime({ offset: true }),
2554
+ last_updated_at: z3.iso.datetime({ offset: true }),
2457
2555
  object: z3.literal("secret-reference")
2458
2556
  });
2459
2557
  var ListSecretReferencesResponseSchema = z3.object({
@@ -2796,7 +2894,7 @@ var GENERIC_GRAPH_ANALYTICS_TOOLS = [
2796
2894
  },
2797
2895
  {
2798
2896
  name: "get_user_requests_analytics",
2799
- 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.",
2800
2898
  method: (analytics, params) => analytics.getUserRequestsAnalytics(params)
2801
2899
  },
2802
2900
  {
@@ -2856,57 +2954,27 @@ function normalizeMetadataFilter(value) {
2856
2954
  }
2857
2955
  return void 0;
2858
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
+ ];
2859
2968
  function normalizeAnalyticsParams(params) {
2860
- const {
2861
- status_codes,
2862
- virtual_key_slugs,
2863
- config_slugs,
2864
- api_key_ids,
2865
- trace_ids,
2866
- span_ids,
2867
- provider_models,
2868
- deployment_ids,
2869
- metadata_filter,
2870
- ...legacyParams
2871
- } = params;
2872
- const normalizedParams = {
2873
- ...legacyParams
2874
- };
2875
- const statusCode = normalizeCommaSeparatedParam(status_codes) ?? normalizeCommaSeparatedParam(legacyParams.status_code);
2876
- if (statusCode !== void 0) {
2877
- normalizedParams.status_code = statusCode;
2969
+ const normalizedParams = { ...params };
2970
+ for (const [alias] of ANALYTICS_PARAM_ALIASES) {
2971
+ delete normalizedParams[alias];
2878
2972
  }
2879
- const virtualKeys = normalizeCommaSeparatedParam(virtual_key_slugs) ?? normalizeCommaSeparatedParam(legacyParams.virtual_keys);
2880
- if (virtualKeys !== void 0) {
2881
- normalizedParams.virtual_keys = virtualKeys;
2882
- }
2883
- const configs = normalizeCommaSeparatedParam(config_slugs) ?? normalizeCommaSeparatedParam(legacyParams.configs);
2884
- if (configs !== void 0) {
2885
- normalizedParams.configs = configs;
2886
- }
2887
- const apiKeyIds = normalizeCommaSeparatedParam(api_key_ids) ?? normalizeCommaSeparatedParam(legacyParams.api_key_ids);
2888
- if (apiKeyIds !== void 0) {
2889
- normalizedParams.api_key_ids = apiKeyIds;
2890
- }
2891
- const metadata = normalizeMetadataFilter(metadata_filter) ?? normalizeMetadataFilter(legacyParams.metadata);
2892
- if (metadata !== void 0) {
2893
- normalizedParams.metadata = metadata;
2894
- }
2895
- const providerModels = normalizeCommaSeparatedParam(provider_models) ?? normalizeCommaSeparatedParam(legacyParams.ai_org_model);
2896
- if (providerModels !== void 0) {
2897
- normalizedParams.ai_org_model = providerModels;
2898
- }
2899
- const deploymentId = normalizeCommaSeparatedParam(deployment_ids) ?? normalizeCommaSeparatedParam(legacyParams.deployment_id);
2900
- if (deploymentId !== void 0) {
2901
- normalizedParams.deployment_id = deploymentId;
2902
- }
2903
- const traceId = normalizeCommaSeparatedParam(trace_ids) ?? normalizeCommaSeparatedParam(legacyParams.trace_id);
2904
- if (traceId !== void 0) {
2905
- normalizedParams.trace_id = traceId;
2906
- }
2907
- const spanId = normalizeCommaSeparatedParam(span_ids) ?? normalizeCommaSeparatedParam(legacyParams.span_id);
2908
- if (spanId !== void 0) {
2909
- 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
+ }
2910
2978
  }
2911
2979
  return normalizedParams;
2912
2980
  }
@@ -2968,7 +3036,7 @@ function registerAnalyticsTools(server, service) {
2968
3036
  server.registerTool(
2969
3037
  "get_token_analytics",
2970
3038
  {
2971
- 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.",
2972
3040
  inputSchema: baseAnalyticsSchema
2973
3041
  },
2974
3042
  async (params) => {
@@ -2978,15 +3046,13 @@ function registerAnalyticsTools(server, service) {
2978
3046
  const dataPoints = analytics.data_points.map((point) => ({
2979
3047
  timestamp: point.timestamp,
2980
3048
  total: point.total,
2981
- prompt: point.prompt,
2982
- completion: point.completion
3049
+ avg: point.avg
2983
3050
  }));
2984
3051
  return jsonResult(
2985
3052
  formatGraphAnalytics(
2986
3053
  {
2987
- total_tokens: analytics.summary.total,
2988
- prompt_tokens: analytics.summary.prompt,
2989
- completion_tokens: analytics.summary.completion
3054
+ total: analytics.summary.total,
3055
+ avg: analytics.summary.avg
2990
3056
  },
2991
3057
  dataPoints
2992
3058
  )
@@ -3100,7 +3166,7 @@ function registerAnalyticsTools(server, service) {
3100
3166
  server.registerTool(
3101
3167
  "get_cache_hit_rate",
3102
3168
  {
3103
- 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.",
3104
3170
  inputSchema: baseAnalyticsSchema
3105
3171
  },
3106
3172
  async (params) => {
@@ -3109,16 +3175,17 @@ function registerAnalyticsTools(server, service) {
3109
3175
  );
3110
3176
  const dataPoints = analytics.data_points.map((point) => ({
3111
3177
  timestamp: point.timestamp,
3178
+ simple_hits: point.simple_hits,
3179
+ semantic_hits: point.semantic_hits,
3112
3180
  rate: point.rate,
3113
- hits: point.hits,
3114
- misses: point.misses
3181
+ cumulative_simple_cache_savings: point.cumulative_simple_cache_savings,
3182
+ cumulative_semantic_cache_savings: point.cumulative_semantic_cache_savings
3115
3183
  }));
3116
3184
  return jsonResult(
3117
3185
  formatGraphAnalytics(
3118
3186
  {
3119
3187
  hit_rate: analytics.summary.rate,
3120
- total_hits: analytics.summary.total_hits,
3121
- total_misses: analytics.summary.total_misses
3188
+ total_hits: analytics.summary.total
3122
3189
  },
3123
3190
  dataPoints
3124
3191
  )
@@ -3142,7 +3209,7 @@ function registerAnalyticsTools(server, service) {
3142
3209
  server.registerTool(
3143
3210
  "get_users_analytics",
3144
3211
  {
3145
- 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.",
3146
3213
  inputSchema: baseAnalyticsSchema
3147
3214
  },
3148
3215
  async (params) => {
@@ -3151,14 +3218,12 @@ function registerAnalyticsTools(server, service) {
3151
3218
  );
3152
3219
  const dataPoints = analytics.data_points.map((point) => ({
3153
3220
  timestamp: point.timestamp,
3154
- active_users: point.active_users,
3155
- new_users: point.new_users
3221
+ total: point.total
3156
3222
  }));
3157
3223
  return jsonResult(
3158
3224
  formatGraphAnalytics(
3159
3225
  {
3160
- total_active_users: analytics.summary.total_active_users,
3161
- total_new_users: analytics.summary.total_new_users
3226
+ total: analytics.summary.total
3162
3227
  },
3163
3228
  dataPoints
3164
3229
  )
@@ -3181,7 +3246,7 @@ function registerAnalyticsTools(server, service) {
3181
3246
  server.registerTool(
3182
3247
  "get_analytics_group_users",
3183
3248
  {
3184
- 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.",
3185
3250
  inputSchema: paginatedAnalyticsSchema
3186
3251
  },
3187
3252
  async (params) => {
@@ -3675,7 +3740,6 @@ function registerConfigsTools(server, service) {
3675
3740
  inputSchema: CONFIGS_TOOL_SCHEMAS.updateConfig,
3676
3741
  annotations: {
3677
3742
  readOnlyHint: false,
3678
- destructiveHint: false,
3679
3743
  idempotentHint: false,
3680
3744
  openWorldHint: false
3681
3745
  }
@@ -4120,7 +4184,6 @@ function registerGuardrailsTools(server, service) {
4120
4184
  annotations: {
4121
4185
  title: "Update Organisation Guardrail Defaults",
4122
4186
  readOnlyHint: false,
4123
- destructiveHint: false,
4124
4187
  idempotentHint: true,
4125
4188
  openWorldHint: true
4126
4189
  }
@@ -4389,31 +4452,68 @@ import { z as z15 } from "zod";
4389
4452
 
4390
4453
  // src/lib/limits.ts
4391
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
+ }
4392
4473
  function buildUsageLimits(params) {
4393
- if (params.credit_limit !== void 0 || params.alert_threshold !== void 0) {
4394
- const limits = {
4395
- type: params.type ?? "cost",
4396
- periodic_reset: params.periodic_reset ?? PERIODIC_RESET_DEFAULT
4397
- };
4398
- if (params.credit_limit !== void 0) {
4399
- 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
+ }
4400
4505
  }
4401
- if (params.alert_threshold !== void 0) {
4402
- 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;
4403
4510
  }
4404
- return limits;
4405
4511
  }
4406
- return void 0;
4512
+ return { ...base, ...supplied };
4407
4513
  }
4408
4514
  function buildRateLimitsRpm(rpmValue) {
4409
4515
  if (rpmValue !== void 0) {
4410
- return [
4411
- {
4412
- type: "requests",
4413
- unit: "rpm",
4414
- value: rpmValue
4415
- }
4416
- ];
4516
+ return buildRateLimits({ value: rpmValue, unit: "rpm" });
4417
4517
  }
4418
4518
  return void 0;
4419
4519
  }
@@ -5167,7 +5267,9 @@ var KEYS_TOOL_SCHEMAS = {
5167
5267
  alert_threshold: z16.coerce.number().min(0).max(100).optional().describe("New alert threshold percentage (0-100)"),
5168
5268
  rate_limit_rpm: z16.coerce.number().positive().optional().describe("New rate limit in requests per minute"),
5169
5269
  rate_limits: z16.array(apiKeyRateLimitSchema).nullable().optional().describe("Replacement request or token rate limits, or null to clear"),
5170
- 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
+ ),
5171
5273
  default_config_id: z16.string().optional().describe("New default configuration ID"),
5172
5274
  default_metadata: z16.record(z16.string(), z16.string()).optional().describe("New default metadata key-value pairs"),
5173
5275
  default_allow_config_override: z16.boolean().optional().describe("Whether callers may override the key's default config"),
@@ -5214,6 +5316,7 @@ var createApiKeySchema = z16.object(KEYS_TOOL_SCHEMAS.createApiKey).superRefine(
5214
5316
  });
5215
5317
  function formatKeyUsageLimits(limits) {
5216
5318
  return limits ? {
5319
+ type: limits.type,
5217
5320
  credit_limit: limits.credit_limit,
5218
5321
  alert_threshold: limits.alert_threshold,
5219
5322
  periodic_reset: limits.periodic_reset
@@ -5359,18 +5462,22 @@ function registerKeysTools(server, service) {
5359
5462
  server.registerTool(
5360
5463
  "update_virtual_key",
5361
5464
  {
5362
- 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.",
5363
5466
  inputSchema: KEYS_TOOL_SCHEMAS.updateVirtualKey
5364
5467
  },
5365
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
+ );
5366
5476
  const result = await service.keys.updateVirtualKey(params.slug, {
5367
5477
  name: params.name,
5368
5478
  key: params.key,
5369
5479
  note: params.note,
5370
- usage_limits: buildUsageLimits({
5371
- credit_limit: params.credit_limit,
5372
- alert_threshold: params.alert_threshold
5373
- }),
5480
+ usage_limits: usageLimits,
5374
5481
  rate_limits: buildRateLimitsRpm(params.rate_limit_rpm),
5375
5482
  deploymentConfig: params.deployment_configurations?.map(
5376
5483
  (configuration) => ({
@@ -5479,18 +5586,22 @@ function registerKeysTools(server, service) {
5479
5586
  server.registerTool(
5480
5587
  "update_api_key",
5481
5588
  {
5482
- 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.",
5483
5590
  inputSchema: KEYS_TOOL_SCHEMAS.updateApiKey
5484
5591
  },
5485
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
+ );
5486
5600
  const result = await service.keys.updateApiKey(params.id, {
5487
5601
  name: params.name,
5488
5602
  description: params.description,
5489
5603
  scopes: params.scopes,
5490
- usage_limits: buildUsageLimits({
5491
- credit_limit: params.credit_limit,
5492
- alert_threshold: params.alert_threshold
5493
- }),
5604
+ usage_limits: usageLimits,
5494
5605
  rate_limits: params.rate_limits === void 0 ? buildRateLimitsRpm(params.rate_limit_rpm) : params.rate_limits,
5495
5606
  ...params.reset_usage !== void 0 ? { reset_usage: params.reset_usage } : {},
5496
5607
  defaults: params.default_config_id !== void 0 || params.default_metadata !== void 0 || params.default_allow_config_override !== void 0 ? {
@@ -6364,7 +6475,10 @@ var MCP_INTEGRATIONS_TOOL_SCHEMAS = {
6364
6475
  "Additional documented or forward-compatible configuration fields. For headers auth, configurations.custom_headers is a string-to-string header map."
6365
6476
  ),
6366
6477
  workspace_id: z20.string().optional().describe(
6367
- "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"
6368
6482
  ),
6369
6483
  secret_mappings: mcpSecretMappingsSchema.optional().describe(
6370
6484
  "Runtime Secret Reference mappings; every configurations.<field> target must be unique"
@@ -6402,7 +6516,8 @@ var MCP_INTEGRATIONS_TOOL_SCHEMAS = {
6402
6516
  id: z20.string().describe("The MCP integration ID or slug")
6403
6517
  },
6404
6518
  listMcpIntegrationCapabilities: {
6405
- 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")
6406
6521
  },
6407
6522
  updateMcpIntegrationCapabilities: {
6408
6523
  id: z20.string().describe("The MCP integration ID or slug"),
@@ -6424,7 +6539,15 @@ var MCP_INTEGRATIONS_TOOL_SCHEMAS = {
6424
6539
  id: z20.string().describe("Workspace ID"),
6425
6540
  enabled: z20.boolean().describe("Whether workspace has access")
6426
6541
  })
6427
- ).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
+ )
6428
6551
  }
6429
6552
  };
6430
6553
  var createMcpIntegrationSchema = z20.object(MCP_INTEGRATIONS_TOOL_SCHEMAS.createMcpIntegration).superRefine((value, ctx) => {
@@ -6627,7 +6750,12 @@ function registerMcpIntegrationsTools(server, service) {
6627
6750
  inputSchema: MCP_INTEGRATIONS_TOOL_SCHEMAS.listMcpIntegrationCapabilities
6628
6751
  },
6629
6752
  async (params) => {
6630
- 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
+ );
6631
6759
  return jsonResult({
6632
6760
  total: result.total,
6633
6761
  capabilities: result.data
@@ -6641,7 +6769,6 @@ function registerMcpIntegrationsTools(server, service) {
6641
6769
  inputSchema: MCP_INTEGRATIONS_TOOL_SCHEMAS.updateMcpIntegrationCapabilities,
6642
6770
  annotations: {
6643
6771
  readOnlyHint: false,
6644
- destructiveHint: false,
6645
6772
  idempotentHint: true,
6646
6773
  openWorldHint: false
6647
6774
  }
@@ -6683,14 +6810,17 @@ function registerMcpIntegrationsTools(server, service) {
6683
6810
  inputSchema: MCP_INTEGRATIONS_TOOL_SCHEMAS.updateMcpIntegrationWorkspaces,
6684
6811
  annotations: {
6685
6812
  readOnlyHint: false,
6686
- destructiveHint: false,
6687
6813
  idempotentHint: true,
6688
6814
  openWorldHint: false
6689
6815
  }
6690
6816
  },
6691
6817
  async (params) => {
6692
6818
  await service.mcpIntegrations.updateMcpIntegrationWorkspaces(params.id, {
6693
- 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
+ } : {}
6694
6824
  });
6695
6825
  return jsonResult({
6696
6826
  message: `Successfully updated workspace access for MCP integration "${params.id}"`,
@@ -6707,7 +6837,9 @@ var MCP_SERVERS_TOOL_SCHEMAS = {
6707
6837
  tags: resourceTagsSchema.optional().describe("Match resources carrying all supplied tags"),
6708
6838
  current_page: CurrentPageSchema,
6709
6839
  page_size: PageSizeSchema.describe("Number of results per page (max 100)"),
6710
- 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)")
6711
6843
  },
6712
6844
  createMcpServer: {
6713
6845
  tags: resourceTagsSchema.nullable().optional().describe(
@@ -6716,7 +6848,10 @@ var MCP_SERVERS_TOOL_SCHEMAS = {
6716
6848
  name: z21.string().describe("Display name for the MCP server"),
6717
6849
  mcp_integration_id: z21.string().describe("ID or slug of the MCP integration this server belongs to"),
6718
6850
  slug: z21.string().optional().describe("Custom slug. Auto-generated if omitted"),
6719
- 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
+ )
6720
6855
  },
6721
6856
  getMcpServer: {
6722
6857
  id: z21.string().describe("The MCP server ID or slug to retrieve")
@@ -6738,7 +6873,8 @@ var MCP_SERVERS_TOOL_SCHEMAS = {
6738
6873
  listMcpServerCapabilities: {
6739
6874
  id: z21.string().describe("The MCP server ID or slug"),
6740
6875
  current_page: CurrentPageSchema,
6741
- 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")
6742
6878
  },
6743
6879
  updateMcpServerCapabilities: {
6744
6880
  id: z21.string().describe("The MCP server ID or slug"),
@@ -6753,7 +6889,8 @@ var MCP_SERVERS_TOOL_SCHEMAS = {
6753
6889
  listMcpServerUserAccess: {
6754
6890
  id: z21.string().describe("The MCP server ID or slug"),
6755
6891
  current_page: CurrentPageSchema,
6756
- 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")
6757
6894
  },
6758
6895
  updateMcpServerUserAccess: {
6759
6896
  id: z21.string().describe("The MCP server ID or slug"),
@@ -6762,7 +6899,10 @@ var MCP_SERVERS_TOOL_SCHEMAS = {
6762
6899
  user_id: z21.string().describe("User ID"),
6763
6900
  enabled: z21.boolean().describe("Whether user has access")
6764
6901
  })
6765
- ).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
+ )
6766
6906
  },
6767
6907
  listMcpServerConnections: {
6768
6908
  id: z21.string().describe("MCP server ID or slug whose connections to list"),
@@ -6789,6 +6929,13 @@ var MCP_SERVERS_TOOL_SCHEMAS = {
6789
6929
  )
6790
6930
  }
6791
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
+ );
6792
6939
  function formatMcpServer(server) {
6793
6940
  return {
6794
6941
  id: server.id,
@@ -6969,7 +7116,8 @@ function registerMcpServersTools(server, service) {
6969
7116
  params.id,
6970
7117
  {
6971
7118
  current_page: params.current_page,
6972
- page_size: params.page_size
7119
+ page_size: params.page_size,
7120
+ type: params.type
6973
7121
  }
6974
7122
  );
6975
7123
  return jsonResult({
@@ -7006,7 +7154,8 @@ function registerMcpServersTools(server, service) {
7006
7154
  params.id,
7007
7155
  {
7008
7156
  current_page: params.current_page,
7009
- page_size: params.page_size
7157
+ page_size: params.page_size,
7158
+ search: params.search
7010
7159
  }
7011
7160
  );
7012
7161
  return jsonResult({
@@ -7020,12 +7169,14 @@ function registerMcpServersTools(server, service) {
7020
7169
  server.registerTool(
7021
7170
  "update_mcp_server_user_access",
7022
7171
  {
7023
- 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.",
7024
7173
  inputSchema: MCP_SERVERS_TOOL_SCHEMAS.updateMcpServerUserAccess
7025
7174
  },
7026
- async (params) => {
7175
+ async (rawParams) => {
7176
+ const params = updateMcpServerUserAccessSchema.parse(rawParams);
7027
7177
  await service.mcpServers.updateMcpServerUserAccess(params.id, {
7028
- 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 } : {}
7029
7180
  });
7030
7181
  return jsonResult({
7031
7182
  message: `Successfully updated user access for MCP server "${params.id}"`,
@@ -7724,7 +7875,7 @@ function registerPromptsTools(server, service) {
7724
7875
  server.registerTool(
7725
7876
  "run_prompt_completion",
7726
7877
  {
7727
- 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.",
7728
7879
  inputSchema: PROMPTS_TOOL_SCHEMAS.runPromptCompletion
7729
7880
  },
7730
7881
  async (params) => {
@@ -7742,6 +7893,9 @@ function registerPromptsTools(server, service) {
7742
7893
  id: result.id,
7743
7894
  model: result.model,
7744
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 } : {},
7745
7899
  finish_reason: choice?.finish_reason ?? null,
7746
7900
  usage: result.usage ? {
7747
7901
  prompt_tokens: result.usage.prompt_tokens,
@@ -7924,14 +8078,16 @@ var PROVIDERS_TOOL_SCHEMAS = {
7924
8078
  credit_limit: z24.coerce.number().positive().optional().describe("New credit limit for usage"),
7925
8079
  alert_threshold: z24.coerce.number().min(0).max(100).optional().describe("New alert threshold percentage (0-100)"),
7926
8080
  usage_limit_type: z24.enum(["cost", "tokens"]).optional().describe(
7927
- "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."
7928
8082
  ),
7929
8083
  periodic_reset: z24.enum(["monthly", "weekly"]).optional().describe(
7930
- "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."
7931
8088
  ),
7932
- rate_limit_value: z24.coerce.number().positive().optional().describe("New rate limit value"),
7933
8089
  rate_limit_unit: z24.enum(["rpm", "rph", "rpd"]).optional().describe(
7934
- "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."
7935
8091
  ),
7936
8092
  expires_at: z24.string().optional().describe("New expiration date in ISO 8601 format"),
7937
8093
  reset_usage: z24.boolean().optional().describe("Set to true to reset accumulated usage metrics")
@@ -7941,6 +8097,18 @@ var PROVIDERS_TOOL_SCHEMAS = {
7941
8097
  workspace_id: z24.string().optional().describe("Workspace ID - required when using organization admin keys")
7942
8098
  }
7943
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
+ });
7944
8112
  function registerProvidersTools(server, service) {
7945
8113
  server.registerTool(
7946
8114
  "list_providers",
@@ -7963,6 +8131,7 @@ function registerProvidersTools(server, service) {
7963
8131
  status: provider.status,
7964
8132
  note: provider.note,
7965
8133
  usage_limits: provider.usage_limits ? {
8134
+ type: provider.usage_limits.type,
7966
8135
  credit_limit: provider.usage_limits.credit_limit,
7967
8136
  alert_threshold: provider.usage_limits.alert_threshold,
7968
8137
  periodic_reset: provider.usage_limits.periodic_reset
@@ -7985,7 +8154,8 @@ function registerProvidersTools(server, service) {
7985
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.",
7986
8155
  inputSchema: PROVIDERS_TOOL_SCHEMAS.createProvider
7987
8156
  },
7988
- async (params) => {
8157
+ async (rawParams) => {
8158
+ const params = createProviderSchema.parse(rawParams);
7989
8159
  const result = await service.providers.createProvider({
7990
8160
  name: params.name,
7991
8161
  integration_id: params.integration_id,
@@ -8029,6 +8199,7 @@ function registerProvidersTools(server, service) {
8029
8199
  status: provider.status,
8030
8200
  note: provider.note,
8031
8201
  usage_limits: provider.usage_limits ? {
8202
+ type: provider.usage_limits.type,
8032
8203
  credit_limit: provider.usage_limits.credit_limit,
8033
8204
  alert_threshold: provider.usage_limits.alert_threshold,
8034
8205
  periodic_reset: provider.usage_limits.periodic_reset
@@ -8047,21 +8218,29 @@ function registerProvidersTools(server, service) {
8047
8218
  server.registerTool(
8048
8219
  "update_provider",
8049
8220
  {
8050
- 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.",
8051
8222
  inputSchema: PROVIDERS_TOOL_SCHEMAS.updateProvider
8052
8223
  },
8053
- 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
+ );
8054
8238
  const result = await service.providers.updateProvider(
8055
8239
  params.slug,
8056
8240
  {
8057
8241
  name: params.name,
8058
8242
  note: params.note,
8059
- usage_limits: buildUsageLimits({
8060
- credit_limit: params.credit_limit,
8061
- alert_threshold: params.alert_threshold,
8062
- type: params.usage_limit_type,
8063
- periodic_reset: params.periodic_reset
8064
- }),
8243
+ usage_limits: usageLimits,
8065
8244
  rate_limits: params.rate_limit_value !== void 0 && params.rate_limit_unit !== void 0 ? buildRateLimits({
8066
8245
  value: params.rate_limit_value,
8067
8246
  unit: params.rate_limit_unit
@@ -8950,6 +9129,14 @@ function formatWorkspaceDefaults(defaults) {
8950
9129
  metadata: defaults.metadata
8951
9130
  };
8952
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
+ }
8953
9140
  function formatWorkspaceSummary(workspace) {
8954
9141
  return {
8955
9142
  id: workspace.id,
@@ -8958,7 +9145,7 @@ function formatWorkspaceSummary(workspace) {
8958
9145
  description: workspace.description,
8959
9146
  created_at: workspace.created_at,
8960
9147
  last_updated_at: workspace.last_updated_at,
8961
- defaults: formatWorkspaceDefaults(workspace.defaults)
9148
+ ...formatWorkspaceFlagsAndLimits(workspace)
8962
9149
  };
8963
9150
  }
8964
9151
  function formatWorkspaceMember(user) {
@@ -8980,7 +9167,7 @@ function formatWorkspaceDetail(workspace) {
8980
9167
  description: workspace.description,
8981
9168
  created_at: workspace.created_at,
8982
9169
  last_updated_at: workspace.last_updated_at,
8983
- defaults: formatWorkspaceDefaults(workspace.defaults),
9170
+ ...formatWorkspaceFlagsAndLimits(workspace),
8984
9171
  users: workspace.users.map(formatWorkspaceMember)
8985
9172
  };
8986
9173
  }
@@ -9327,7 +9514,9 @@ var DESTRUCTIVE_TOOL_PREFIXES = [
9327
9514
  "delete_",
9328
9515
  "remove_",
9329
9516
  "cancel_",
9330
- "reset_"
9517
+ "reset_",
9518
+ "update_",
9519
+ "archive_"
9331
9520
  ];
9332
9521
  var ENTERPRISE_GATED_TOOL_NAMES = /* @__PURE__ */ new Set([
9333
9522
  "get_cost_analytics",
@@ -9460,12 +9649,12 @@ function getToolErrorMessage(error) {
9460
9649
  return String(error);
9461
9650
  }
9462
9651
  var STANDARD_TOOL_OUTPUT_SCHEMA = {
9463
- ok: z29.boolean().describe("Whether the tool call succeeded and returned structured data"),
9464
- 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"),
9465
9654
  error: z29.object({
9466
- message: z29.string().describe("Human-readable error message"),
9467
- details: z29.unknown().optional().describe("Optional structured error details")
9468
- }).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")
9469
9658
  };
9470
9659
  var TOOL_SUCCESS_DATA_SCHEMAS = {
9471
9660
  create_access_policy: CreateAccessPolicyResponseSchema,
@@ -9483,7 +9672,10 @@ var TOOL_SUCCESS_DATA_SCHEMAS = {
9483
9672
  warning: z29.string().describe("Required handling guidance for the one-time secret"),
9484
9673
  id: z29.string().uuid().describe("Rotated API key UUID"),
9485
9674
  key: z29.string().describe("New API key secret, returned only once"),
9486
- 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")
9487
9679
  }),
9488
9680
  create_secret_reference: z29.object({
9489
9681
  message: z29.string().describe("Creation confirmation"),
@@ -9500,9 +9692,9 @@ var TOOL_SUCCESS_DATA_SCHEMAS = {
9500
9692
  manager_type: SecretManagerTypeSchema.describe(
9501
9693
  "External secret manager type"
9502
9694
  ),
9503
- status: z29.literal("ACTIVE").describe("Current reference status"),
9504
- created_at: z29.iso.datetime().describe("ISO 8601 creation timestamp"),
9505
- 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")
9506
9698
  })
9507
9699
  ).describe(
9508
9700
  "Current page of Secret References without authentication values"
@@ -9521,10 +9713,10 @@ var TOOL_SUCCESS_DATA_SCHEMAS = {
9521
9713
  secret_key: z29.string().nullable().describe("Selected key within a structured secret"),
9522
9714
  allow_all_workspaces: z29.boolean().describe("Whether all workspaces may use the reference"),
9523
9715
  tags: z29.record(z29.string(), z29.string()).nullable().describe("String metadata tags"),
9524
- status: z29.literal("ACTIVE").describe("Current reference status"),
9716
+ status: z29.string().describe("Current reference status"),
9525
9717
  created_by: z29.string().describe("Creator identifier"),
9526
- created_at: z29.iso.datetime().describe("ISO 8601 creation timestamp"),
9527
- 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"),
9528
9720
  auth_config: z29.record(z29.string(), z29.unknown()).describe("Authentication configuration with sensitive values redacted"),
9529
9721
  object: z29.literal("secret-reference").describe("Portkey object type")
9530
9722
  }),
@@ -9542,7 +9734,7 @@ function getToolOutputSchema(toolName) {
9542
9734
  if (!dataSchema) return STANDARD_TOOL_OUTPUT_SCHEMA;
9543
9735
  return {
9544
9736
  ...STANDARD_TOOL_OUTPUT_SCHEMA,
9545
- data: dataSchema.optional().describe("Structured success payload when ok is true")
9737
+ data: dataSchema.optional().describe("Success payload")
9546
9738
  };
9547
9739
  }
9548
9740
  function isStandardToolEnvelope(value) {
@@ -9604,10 +9796,31 @@ function normalizeToolResult(result) {
9604
9796
  structuredContent: envelope
9605
9797
  };
9606
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
+ }
9607
9817
  function wrapToolCallback(toolName, callback) {
9608
9818
  return async (...args) => {
9609
9819
  try {
9610
- return normalizeToolResult(await callback(...args));
9820
+ return enforceToolResultLimit(
9821
+ toolName,
9822
+ normalizeToolResult(await callback(...args))
9823
+ );
9611
9824
  } catch (error) {
9612
9825
  const message = getToolErrorMessage(error);
9613
9826
  const isValidationError = error instanceof z29.ZodError;
@@ -9616,23 +9829,64 @@ function wrapToolCallback(toolName, callback) {
9616
9829
  error: message,
9617
9830
  metadata: { toolName }
9618
9831
  });
9619
- return normalizeToolResult({
9620
- content: [{ type: "text", text }],
9621
- isError: true
9622
- });
9832
+ return enforceToolResultLimit(
9833
+ toolName,
9834
+ normalizeToolResult({
9835
+ content: [{ type: "text", text }],
9836
+ isError: true
9837
+ })
9838
+ );
9623
9839
  }
9624
9840
  };
9625
9841
  }
9626
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
+ }
9627
9873
  function normalizeRegistrationSchema(schema) {
9628
- if (!isRecord(schema) || "~standard" in schema) return schema;
9629
- let normalized = registrationSchemas.get(schema);
9630
- if (!normalized) {
9631
- normalized = z29.object(schema);
9632
- registrationSchemas.set(schema, normalized);
9633
- }
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);
9634
9880
  return normalized;
9635
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
+ }
9636
9890
  function createSafeToolServer(server) {
9637
9891
  const originalRegisterTool = server.registerTool.bind(server);
9638
9892
  const safeServer = Object.create(server);
@@ -9648,7 +9902,7 @@ function createSafeToolServer(server) {
9648
9902
  ...description === void 0 ? {} : { description },
9649
9903
  inputSchema: normalizeRegistrationSchema(config.inputSchema),
9650
9904
  outputSchema: normalizeRegistrationSchema(
9651
- config.outputSchema ?? getToolOutputSchema(name)
9905
+ config.outputSchema ?? getRegistrationOutputSchema(name)
9652
9906
  ),
9653
9907
  annotations: {
9654
9908
  ...inferToolAnnotations(name),
@@ -9852,6 +10106,7 @@ function createMcpServer(options = {}) {
9852
10106
  // src/index.ts
9853
10107
  function main() {
9854
10108
  try {
10109
+ assertByteLimitsConfigured();
9855
10110
  if (!process.env.PORTKEY_API_KEY) {
9856
10111
  Logger.warn(
9857
10112
  "PORTKEY_API_KEY is not set; tool calls will fail until it is configured."