portkey-admin-mcp 0.16.4 → 0.16.6

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/server.js CHANGED
@@ -157,6 +157,70 @@ var FetchError = class extends Error {
157
157
  status;
158
158
  response;
159
159
  };
160
+ var DEFAULT_MAX_UPSTREAM_BODY_BYTES = 8 * 1024 * 1024;
161
+ var DEFAULT_MAX_TOOL_RESULT_BYTES = 4 * 1024 * 1024;
162
+ var MAX_CONFIGURABLE_BYTES = 1024 * 1024 * 1024;
163
+ var MAX_UPSTREAM_BODY_BYTES_ENV = "PORTKEY_MAX_UPSTREAM_BODY_BYTES";
164
+ var MAX_TOOL_RESULT_BYTES_ENV = "PORTKEY_MAX_TOOL_RESULT_BYTES";
165
+ function resolveByteLimit(envName, fallback) {
166
+ const raw = process.env[envName]?.trim();
167
+ if (!raw) return fallback;
168
+ const parsed = /^\d+$/.test(raw) ? Number(raw) : Number.NaN;
169
+ if (!Number.isSafeInteger(parsed) || parsed < 1 || parsed > MAX_CONFIGURABLE_BYTES) {
170
+ throw new Error(
171
+ `Invalid ${envName} value: ${raw}. Must be a positive integer number of bytes (1-${MAX_CONFIGURABLE_BYTES})`
172
+ );
173
+ }
174
+ return parsed;
175
+ }
176
+ function getMaxUpstreamBodyBytes() {
177
+ return resolveByteLimit(
178
+ MAX_UPSTREAM_BODY_BYTES_ENV,
179
+ DEFAULT_MAX_UPSTREAM_BODY_BYTES
180
+ );
181
+ }
182
+ function getMaxToolResultBytes() {
183
+ return resolveByteLimit(
184
+ MAX_TOOL_RESULT_BYTES_ENV,
185
+ DEFAULT_MAX_TOOL_RESULT_BYTES
186
+ );
187
+ }
188
+ function assertByteLimitsConfigured() {
189
+ getMaxUpstreamBodyBytes();
190
+ getMaxToolResultBytes();
191
+ }
192
+ var ResponseBodyTooLargeError = class extends Error {
193
+ constructor(limit) {
194
+ super(`Response body is larger than the ${limit}-byte limit`);
195
+ this.limit = limit;
196
+ this.name = "ResponseBodyTooLargeError";
197
+ }
198
+ limit;
199
+ };
200
+ async function readBoundedText(response, maxBytes) {
201
+ if (!response.body) return "";
202
+ const reader = response.body.getReader();
203
+ const chunks = [];
204
+ let received = 0;
205
+ try {
206
+ for (; ; ) {
207
+ const { done, value } = await reader.read();
208
+ if (done) break;
209
+ received += value.byteLength;
210
+ if (received > maxBytes) {
211
+ await reader.cancel().catch(() => void 0);
212
+ throw new ResponseBodyTooLargeError(maxBytes);
213
+ }
214
+ chunks.push(value);
215
+ }
216
+ } finally {
217
+ reader.releaseLock();
218
+ }
219
+ return new TextDecoder().decode(Buffer.concat(chunks));
220
+ }
221
+ async function readBoundedJson(response, maxBytes) {
222
+ return JSON.parse(await readBoundedText(response, maxBytes));
223
+ }
160
224
  async function fetchWithTimeout(url, options = {}) {
161
225
  const { timeout = 3e4, ...fetchOptions } = options;
162
226
  return fetch(url, {
@@ -176,9 +240,9 @@ function buildQueryString(params) {
176
240
  if (entries.length === 0) return "";
177
241
  return `?${new URLSearchParams(entries).toString()}`;
178
242
  }
179
- async function parseErrorResponse(response) {
243
+ async function parseErrorResponse(response, maxBytes = DEFAULT_MAX_UPSTREAM_BODY_BYTES) {
180
244
  try {
181
- const body = await response.json();
245
+ const body = await readBoundedJson(response, maxBytes);
182
246
  const err = body.error ?? body.data ?? body ?? {};
183
247
  const code = err?.errorCode ?? err?.code;
184
248
  return {
@@ -188,10 +252,10 @@ async function parseErrorResponse(response) {
188
252
  code,
189
253
  type: err?.type
190
254
  };
191
- } catch {
255
+ } catch (error) {
192
256
  return {
193
257
  status_code: response.status,
194
- message: `HTTP error! status: ${response.status}`
258
+ message: error instanceof ResponseBodyTooLargeError ? `HTTP error! status: ${response.status} (error body over the ${maxBytes}-byte limit)` : `HTTP error! status: ${response.status}`
195
259
  };
196
260
  }
197
261
  }
@@ -463,6 +527,7 @@ var BaseService = class {
463
527
  paramKeys: options.params ? Object.keys(options.params) : []
464
528
  }
465
529
  });
530
+ const maxBodyBytes = getMaxUpstreamBodyBytes();
466
531
  try {
467
532
  const response = await fetchWithTimeout(url, {
468
533
  method,
@@ -473,7 +538,7 @@ var BaseService = class {
473
538
  });
474
539
  const duration_ms = Date.now() - startTime;
475
540
  if (!response.ok) {
476
- const apiError = await parseErrorResponse(response);
541
+ const apiError = await parseErrorResponse(response, maxBodyBytes);
477
542
  Logger.error("HTTP request failed", {
478
543
  requestId,
479
544
  method,
@@ -494,7 +559,16 @@ var BaseService = class {
494
559
  if (options.allowNoContent && response.status === 204) {
495
560
  return NO_CONTENT;
496
561
  }
497
- return await response.json();
562
+ try {
563
+ return await readBoundedJson(response, maxBodyBytes);
564
+ } catch (error) {
565
+ if (error instanceof ResponseBodyTooLargeError) {
566
+ throw new Error(
567
+ `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.`
568
+ );
569
+ }
570
+ throw error;
571
+ }
498
572
  } catch (error) {
499
573
  const duration_ms = Date.now() - startTime;
500
574
  if (!(error instanceof FetchError)) {
@@ -570,9 +644,9 @@ var BaseService = class {
570
644
  })
571
645
  );
572
646
  }
573
- async put(path, body) {
647
+ async put(path, body, params) {
574
648
  return this.rejectNoContent(
575
- await this.executeRequest("PUT", path, { body })
649
+ await this.executeRequest("PUT", path, { body, params })
576
650
  );
577
651
  }
578
652
  /**
@@ -644,7 +718,7 @@ var AnalyticsService = class extends BaseService {
644
718
  * Helper method to build query params from analytics parameters
645
719
  */
646
720
  buildAnalyticsParams(params) {
647
- const baseParams = {
721
+ return {
648
722
  time_of_generation_min: params.time_of_generation_min,
649
723
  time_of_generation_max: params.time_of_generation_max,
650
724
  total_units_min: params.total_units_min,
@@ -661,7 +735,7 @@ var AnalyticsService = class extends BaseService {
661
735
  virtual_keys: params.virtual_keys,
662
736
  configs: params.configs,
663
737
  workspace_slug: params.workspace_slug,
664
- include_all_workspaces: params.include_all_workspaces === void 0 ? void 0 : String(params.include_all_workspaces),
738
+ include_all_workspaces: params.include_all_workspaces,
665
739
  exclude_workspace_slugs: params.exclude_workspace_slugs,
666
740
  api_key_ids: params.api_key_ids,
667
741
  metadata: params.metadata,
@@ -669,21 +743,14 @@ var AnalyticsService = class extends BaseService {
669
743
  deployment_id: params.deployment_id,
670
744
  trace_id: params.trace_id,
671
745
  span_id: params.span_id,
672
- prompt_slug: params.prompt_slug
746
+ prompt_slug: params.prompt_slug,
747
+ current_page: params.current_page,
748
+ page_size: params.page_size,
749
+ order_by: params.order_by,
750
+ order_by_type: params.order_by_type,
751
+ columns: params.columns,
752
+ include_total: params.include_total
673
753
  };
674
- if ("current_page" in params) {
675
- baseParams.current_page = params.current_page;
676
- }
677
- if ("page_size" in params) {
678
- baseParams.page_size = params.page_size;
679
- }
680
- if ("order_by" in params) baseParams.order_by = params.order_by;
681
- if ("order_by_type" in params)
682
- baseParams.order_by_type = params.order_by_type;
683
- if ("columns" in params) baseParams.columns = params.columns;
684
- if ("include_total" in params)
685
- baseParams.include_total = params.include_total;
686
- return baseParams;
687
754
  }
688
755
  // ==================== Cost Analytics ====================
689
756
  async getCostAnalytics(params) {
@@ -1595,9 +1662,10 @@ var McpIntegrationsService = class extends BaseService {
1595
1662
  `/mcp-integrations/${this.encodePathSegment(id)}/metadata`
1596
1663
  );
1597
1664
  }
1598
- async listMcpIntegrationCapabilities(id) {
1665
+ async listMcpIntegrationCapabilities(id, params) {
1599
1666
  return this.get(
1600
- `/mcp-integrations/${this.encodePathSegment(id)}/capabilities`
1667
+ `/mcp-integrations/${this.encodePathSegment(id)}/capabilities`,
1668
+ { type: params?.type }
1601
1669
  );
1602
1670
  }
1603
1671
  async updateMcpIntegrationCapabilities(id, data) {
@@ -1641,6 +1709,8 @@ var McpServersService = class extends BaseService {
1641
1709
  current_page: params?.current_page,
1642
1710
  page_size: params?.page_size,
1643
1711
  workspace_id: params?.workspace_id,
1712
+ id: params?.id,
1713
+ search: params?.search,
1644
1714
  tags: params?.tags === void 0 ? void 0 : JSON.stringify(params.tags)
1645
1715
  });
1646
1716
  }
@@ -1669,7 +1739,8 @@ var McpServersService = class extends BaseService {
1669
1739
  `/mcp-servers/${this.encodePathSegment(id)}/capabilities`,
1670
1740
  {
1671
1741
  current_page: params?.current_page,
1672
- page_size: params?.page_size
1742
+ page_size: params?.page_size,
1743
+ type: params?.type
1673
1744
  }
1674
1745
  );
1675
1746
  }
@@ -1685,7 +1756,8 @@ var McpServersService = class extends BaseService {
1685
1756
  `/mcp-servers/${this.encodePathSegment(id)}/user-access`,
1686
1757
  {
1687
1758
  current_page: params?.current_page,
1688
- page_size: params?.page_size
1759
+ page_size: params?.page_size,
1760
+ search: params?.search
1689
1761
  }
1690
1762
  );
1691
1763
  }
@@ -1748,6 +1820,7 @@ var PartialsService = class extends BaseService {
1748
1820
 
1749
1821
  // src/services/prompts.service.ts
1750
1822
  import { isDeepStrictEqual } from "node:util";
1823
+ var PROMOTE_INCOMPLETE_SOURCE_MESSAGE = "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)";
1751
1824
  var PromptsService = class extends BaseService {
1752
1825
  async createPrompt(data) {
1753
1826
  const { is_raw_template, ...rest } = data;
@@ -1784,6 +1857,8 @@ var PromptsService = class extends BaseService {
1784
1857
  string: raw.string ?? "",
1785
1858
  parameters: raw.parameters ?? {},
1786
1859
  model: raw.model,
1860
+ ai_model_id: raw.ai_model_id,
1861
+ finetune_id: raw.finetune_id,
1787
1862
  virtual_key: raw.virtual_key,
1788
1863
  functions: raw.functions ?? void 0,
1789
1864
  tools: raw.tools ?? void 0,
@@ -1795,12 +1870,14 @@ var PromptsService = class extends BaseService {
1795
1870
  object: "prompt"
1796
1871
  };
1797
1872
  }
1798
- async updatePrompt(promptId, data) {
1873
+ async updatePrompt(promptId, data, options = {}) {
1799
1874
  const { template_metadata, is_raw_template, ...rest } = data;
1800
1875
  const body = {
1801
1876
  ...rest,
1802
- // Enable partial updates so missing version fields are backfilled from latest version
1803
- patch: true
1877
+ // Partial updates backfill missing version fields from the latest
1878
+ // version. Callers that send a complete version turn this off so absent
1879
+ // fields are cleared instead of inherited.
1880
+ patch: options.patch ?? true
1804
1881
  };
1805
1882
  if (template_metadata !== void 0) {
1806
1883
  body.prompt_metadata = template_metadata;
@@ -2027,24 +2104,40 @@ var PromptsService = class extends BaseService {
2027
2104
  data.target_collection_id
2028
2105
  );
2029
2106
  if (existingTarget) {
2030
- const updateResult = await this.updatePrompt(existingTarget.id, {
2031
- string: sourceVersion.string,
2032
- parameters: sourceVersion.parameters,
2033
- model: sourceVersion.model,
2034
- virtual_key: data.virtual_key || sourceVersion.virtual_key,
2035
- functions: sourceVersion.functions,
2036
- tools: sourceVersion.tools,
2037
- tool_choice: sourceVersion.tool_choice,
2038
- is_raw_template: sourceVersion.is_raw_template,
2039
- version_description: `Promoted from ${sourcePrompt.slug} v${sourceVersion.version_number}`,
2040
- template_metadata: {
2041
- ...sourceVersion.template_metadata,
2042
- env: data.target_env,
2043
- promoted_from: sourcePrompt.slug,
2044
- promoted_from_version: sourceVersion.version_number.toString(),
2045
- promoted_at: (/* @__PURE__ */ new Date()).toISOString()
2046
- }
2047
- });
2107
+ const virtualKey2 = data.virtual_key || sourceVersion.virtual_key;
2108
+ if (!sourceVersion.string || !(sourceVersion.model || sourceVersion.ai_model_id || sourceVersion.finetune_id) || !virtualKey2) {
2109
+ throw new Error(PROMOTE_INCOMPLETE_SOURCE_MESSAGE);
2110
+ }
2111
+ const updateResult = await this.updatePrompt(
2112
+ existingTarget.id,
2113
+ {
2114
+ string: sourceVersion.string,
2115
+ parameters: sourceVersion.parameters ?? {},
2116
+ ...sourceVersion.model && { model: sourceVersion.model },
2117
+ ...sourceVersion.ai_model_id && {
2118
+ ai_model_id: sourceVersion.ai_model_id
2119
+ },
2120
+ ...sourceVersion.finetune_id && {
2121
+ finetune_id: sourceVersion.finetune_id
2122
+ },
2123
+ virtual_key: virtualKey2,
2124
+ functions: sourceVersion.functions ?? [],
2125
+ tools: sourceVersion.tools ?? [],
2126
+ ...sourceVersion.tool_choice !== void 0 && {
2127
+ tool_choice: sourceVersion.tool_choice
2128
+ },
2129
+ is_raw_template: sourceVersion.is_raw_template ?? false,
2130
+ version_description: `Promoted from ${sourcePrompt.slug} v${sourceVersion.version_number}`,
2131
+ template_metadata: {
2132
+ ...sourceVersion.template_metadata,
2133
+ env: data.target_env,
2134
+ promoted_from: sourcePrompt.slug,
2135
+ promoted_from_version: sourceVersion.version_number.toString(),
2136
+ promoted_at: (/* @__PURE__ */ new Date()).toISOString()
2137
+ }
2138
+ },
2139
+ { patch: false }
2140
+ );
2048
2141
  return {
2049
2142
  source_prompt_id: data.source_prompt_id,
2050
2143
  source_version_id: sourceVersion.id,
@@ -2060,13 +2153,22 @@ var PromptsService = class extends BaseService {
2060
2153
  "Cannot promote prompt: source version has no virtual_key and none was provided"
2061
2154
  );
2062
2155
  }
2156
+ if (!(sourceVersion.model || sourceVersion.ai_model_id || sourceVersion.finetune_id)) {
2157
+ throw new Error(PROMOTE_INCOMPLETE_SOURCE_MESSAGE);
2158
+ }
2063
2159
  const createResult = await this.createPrompt({
2064
2160
  name: targetName,
2065
2161
  collection_id: data.target_collection_id,
2066
2162
  string: sourceVersion.string,
2067
2163
  parameters: sourceVersion.parameters,
2068
2164
  virtual_key: virtualKey,
2069
- model: sourceVersion.model,
2165
+ ...sourceVersion.model && { model: sourceVersion.model },
2166
+ ...sourceVersion.ai_model_id && {
2167
+ ai_model_id: sourceVersion.ai_model_id
2168
+ },
2169
+ ...sourceVersion.finetune_id && {
2170
+ finetune_id: sourceVersion.finetune_id
2171
+ },
2070
2172
  functions: sourceVersion.functions,
2071
2173
  tools: sourceVersion.tools,
2072
2174
  tool_choice: sourceVersion.tool_choice,
@@ -2128,12 +2230,17 @@ var ProvidersService = class extends BaseService {
2128
2230
  });
2129
2231
  }
2130
2232
  async updateProvider(slug, data, workspaceId) {
2131
- const path = workspaceId ? `/providers/${this.encodePathSegment(slug)}?workspace_id=${encodeURIComponent(workspaceId)}` : `/providers/${this.encodePathSegment(slug)}`;
2132
- return this.put(path, data);
2233
+ return this.put(
2234
+ `/providers/${this.encodePathSegment(slug)}`,
2235
+ data,
2236
+ { workspace_id: workspaceId || void 0 }
2237
+ );
2133
2238
  }
2134
2239
  async deleteProvider(slug, workspaceId) {
2135
- const path = workspaceId ? `/providers/${this.encodePathSegment(slug)}?workspace_id=${encodeURIComponent(workspaceId)}` : `/providers/${this.encodePathSegment(slug)}`;
2136
- const result = await this.delete(path);
2240
+ const result = await this.delete(
2241
+ `/providers/${this.encodePathSegment(slug)}`,
2242
+ { workspace_id: workspaceId || void 0 }
2243
+ );
2137
2244
  return isNoContent(result) ? {} : result;
2138
2245
  }
2139
2246
  };
@@ -2360,7 +2467,7 @@ function getSharedServiceCacheKey(apiKey) {
2360
2467
  const keyDigest = createHmac("sha256", SERVICE_CACHE_HMAC_KEY).update(apiKey).digest("hex");
2361
2468
  return JSON.stringify({
2362
2469
  apiKey: keyDigest,
2363
- baseUrl: process.env.PORTKEY_BASE_URL?.trim() || ""
2470
+ baseUrl: process.env.PORTKEY_BASE_URL ?? DEFAULT_BASE_URL
2364
2471
  });
2365
2472
  }
2366
2473
  var sharedPortkeyServices = /* @__PURE__ */ new Map();
@@ -2390,8 +2497,7 @@ var PortkeyService = class {
2390
2497
  health;
2391
2498
  constructor(apiKey) {
2392
2499
  const resolvedApiKey = resolvePortkeyApiKey(apiKey);
2393
- const resolvedBaseUrl = process.env.PORTKEY_BASE_URL ?? "https://api.portkey.ai/v1";
2394
- validateUrl(resolvedBaseUrl);
2500
+ const resolvedBaseUrl = process.env.PORTKEY_BASE_URL ?? DEFAULT_BASE_URL;
2395
2501
  this.accessPolicies = new AccessPoliciesService(
2396
2502
  resolvedApiKey,
2397
2503
  resolvedBaseUrl
@@ -2465,8 +2571,8 @@ var SecretReferenceListItemSchema = z3.object({
2465
2571
  slug: z3.string(),
2466
2572
  manager_type: SecretManagerTypeSchema,
2467
2573
  status: z3.literal("ACTIVE"),
2468
- created_at: z3.iso.datetime(),
2469
- last_updated_at: z3.iso.datetime(),
2574
+ created_at: z3.iso.datetime({ offset: true }),
2575
+ last_updated_at: z3.iso.datetime({ offset: true }),
2470
2576
  object: z3.literal("secret-reference")
2471
2577
  });
2472
2578
  var ListSecretReferencesResponseSchema = z3.object({
@@ -2809,7 +2915,7 @@ var GENERIC_GRAPH_ANALYTICS_TOOLS = [
2809
2915
  },
2810
2916
  {
2811
2917
  name: "get_user_requests_analytics",
2812
- 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.",
2918
+ 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.",
2813
2919
  method: (analytics, params) => analytics.getUserRequestsAnalytics(params)
2814
2920
  },
2815
2921
  {
@@ -2869,57 +2975,27 @@ function normalizeMetadataFilter(value) {
2869
2975
  }
2870
2976
  return void 0;
2871
2977
  }
2978
+ var ANALYTICS_PARAM_ALIASES = [
2979
+ ["status_codes", "status_code", normalizeCommaSeparatedParam],
2980
+ ["virtual_key_slugs", "virtual_keys", normalizeCommaSeparatedParam],
2981
+ ["config_slugs", "configs", normalizeCommaSeparatedParam],
2982
+ ["api_key_ids", "api_key_ids", normalizeCommaSeparatedParam],
2983
+ ["metadata_filter", "metadata", normalizeMetadataFilter],
2984
+ ["provider_models", "ai_org_model", normalizeCommaSeparatedParam],
2985
+ ["deployment_ids", "deployment_id", normalizeCommaSeparatedParam],
2986
+ ["trace_ids", "trace_id", normalizeCommaSeparatedParam],
2987
+ ["span_ids", "span_id", normalizeCommaSeparatedParam]
2988
+ ];
2872
2989
  function normalizeAnalyticsParams(params) {
2873
- const {
2874
- status_codes,
2875
- virtual_key_slugs,
2876
- config_slugs,
2877
- api_key_ids,
2878
- trace_ids,
2879
- span_ids,
2880
- provider_models,
2881
- deployment_ids,
2882
- metadata_filter,
2883
- ...legacyParams
2884
- } = params;
2885
- const normalizedParams = {
2886
- ...legacyParams
2887
- };
2888
- const statusCode = normalizeCommaSeparatedParam(status_codes) ?? normalizeCommaSeparatedParam(legacyParams.status_code);
2889
- if (statusCode !== void 0) {
2890
- normalizedParams.status_code = statusCode;
2891
- }
2892
- const virtualKeys = normalizeCommaSeparatedParam(virtual_key_slugs) ?? normalizeCommaSeparatedParam(legacyParams.virtual_keys);
2893
- if (virtualKeys !== void 0) {
2894
- normalizedParams.virtual_keys = virtualKeys;
2895
- }
2896
- const configs = normalizeCommaSeparatedParam(config_slugs) ?? normalizeCommaSeparatedParam(legacyParams.configs);
2897
- if (configs !== void 0) {
2898
- normalizedParams.configs = configs;
2899
- }
2900
- const apiKeyIds = normalizeCommaSeparatedParam(api_key_ids) ?? normalizeCommaSeparatedParam(legacyParams.api_key_ids);
2901
- if (apiKeyIds !== void 0) {
2902
- normalizedParams.api_key_ids = apiKeyIds;
2903
- }
2904
- const metadata = normalizeMetadataFilter(metadata_filter) ?? normalizeMetadataFilter(legacyParams.metadata);
2905
- if (metadata !== void 0) {
2906
- normalizedParams.metadata = metadata;
2907
- }
2908
- const providerModels = normalizeCommaSeparatedParam(provider_models) ?? normalizeCommaSeparatedParam(legacyParams.ai_org_model);
2909
- if (providerModels !== void 0) {
2910
- normalizedParams.ai_org_model = providerModels;
2990
+ const normalizedParams = { ...params };
2991
+ for (const [alias] of ANALYTICS_PARAM_ALIASES) {
2992
+ delete normalizedParams[alias];
2911
2993
  }
2912
- const deploymentId = normalizeCommaSeparatedParam(deployment_ids) ?? normalizeCommaSeparatedParam(legacyParams.deployment_id);
2913
- if (deploymentId !== void 0) {
2914
- normalizedParams.deployment_id = deploymentId;
2915
- }
2916
- const traceId = normalizeCommaSeparatedParam(trace_ids) ?? normalizeCommaSeparatedParam(legacyParams.trace_id);
2917
- if (traceId !== void 0) {
2918
- normalizedParams.trace_id = traceId;
2919
- }
2920
- const spanId = normalizeCommaSeparatedParam(span_ids) ?? normalizeCommaSeparatedParam(legacyParams.span_id);
2921
- if (spanId !== void 0) {
2922
- normalizedParams.span_id = spanId;
2994
+ for (const [alias, legacy, normalize] of ANALYTICS_PARAM_ALIASES) {
2995
+ const value = normalize(params[alias]) ?? normalize(params[legacy]);
2996
+ if (value !== void 0) {
2997
+ normalizedParams[legacy] = value;
2998
+ }
2923
2999
  }
2924
3000
  return normalizedParams;
2925
3001
  }
@@ -2981,7 +3057,7 @@ function registerAnalyticsTools(server, service) {
2981
3057
  server.registerTool(
2982
3058
  "get_token_analytics",
2983
3059
  {
2984
- 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.",
3060
+ 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.",
2985
3061
  inputSchema: baseAnalyticsSchema
2986
3062
  },
2987
3063
  async (params) => {
@@ -2991,15 +3067,13 @@ function registerAnalyticsTools(server, service) {
2991
3067
  const dataPoints = analytics.data_points.map((point) => ({
2992
3068
  timestamp: point.timestamp,
2993
3069
  total: point.total,
2994
- prompt: point.prompt,
2995
- completion: point.completion
3070
+ avg: point.avg
2996
3071
  }));
2997
3072
  return jsonResult(
2998
3073
  formatGraphAnalytics(
2999
3074
  {
3000
- total_tokens: analytics.summary.total,
3001
- prompt_tokens: analytics.summary.prompt,
3002
- completion_tokens: analytics.summary.completion
3075
+ total: analytics.summary.total,
3076
+ avg: analytics.summary.avg
3003
3077
  },
3004
3078
  dataPoints
3005
3079
  )
@@ -3113,7 +3187,7 @@ function registerAnalyticsTools(server, service) {
3113
3187
  server.registerTool(
3114
3188
  "get_cache_hit_rate",
3115
3189
  {
3116
- 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.",
3190
+ 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.",
3117
3191
  inputSchema: baseAnalyticsSchema
3118
3192
  },
3119
3193
  async (params) => {
@@ -3122,16 +3196,17 @@ function registerAnalyticsTools(server, service) {
3122
3196
  );
3123
3197
  const dataPoints = analytics.data_points.map((point) => ({
3124
3198
  timestamp: point.timestamp,
3199
+ simple_hits: point.simple_hits,
3200
+ semantic_hits: point.semantic_hits,
3125
3201
  rate: point.rate,
3126
- hits: point.hits,
3127
- misses: point.misses
3202
+ cumulative_simple_cache_savings: point.cumulative_simple_cache_savings,
3203
+ cumulative_semantic_cache_savings: point.cumulative_semantic_cache_savings
3128
3204
  }));
3129
3205
  return jsonResult(
3130
3206
  formatGraphAnalytics(
3131
3207
  {
3132
3208
  hit_rate: analytics.summary.rate,
3133
- total_hits: analytics.summary.total_hits,
3134
- total_misses: analytics.summary.total_misses
3209
+ total_hits: analytics.summary.total
3135
3210
  },
3136
3211
  dataPoints
3137
3212
  )
@@ -3155,7 +3230,7 @@ function registerAnalyticsTools(server, service) {
3155
3230
  server.registerTool(
3156
3231
  "get_users_analytics",
3157
3232
  {
3158
- 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.",
3233
+ 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.",
3159
3234
  inputSchema: baseAnalyticsSchema
3160
3235
  },
3161
3236
  async (params) => {
@@ -3164,14 +3239,12 @@ function registerAnalyticsTools(server, service) {
3164
3239
  );
3165
3240
  const dataPoints = analytics.data_points.map((point) => ({
3166
3241
  timestamp: point.timestamp,
3167
- active_users: point.active_users,
3168
- new_users: point.new_users
3242
+ total: point.total
3169
3243
  }));
3170
3244
  return jsonResult(
3171
3245
  formatGraphAnalytics(
3172
3246
  {
3173
- total_active_users: analytics.summary.total_active_users,
3174
- total_new_users: analytics.summary.total_new_users
3247
+ total: analytics.summary.total
3175
3248
  },
3176
3249
  dataPoints
3177
3250
  )
@@ -3194,7 +3267,7 @@ function registerAnalyticsTools(server, service) {
3194
3267
  server.registerTool(
3195
3268
  "get_analytics_group_users",
3196
3269
  {
3197
- 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.",
3270
+ 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.",
3198
3271
  inputSchema: paginatedAnalyticsSchema
3199
3272
  },
3200
3273
  async (params) => {
@@ -3688,7 +3761,6 @@ function registerConfigsTools(server, service) {
3688
3761
  inputSchema: CONFIGS_TOOL_SCHEMAS.updateConfig,
3689
3762
  annotations: {
3690
3763
  readOnlyHint: false,
3691
- destructiveHint: false,
3692
3764
  idempotentHint: false,
3693
3765
  openWorldHint: false
3694
3766
  }
@@ -4133,7 +4205,6 @@ function registerGuardrailsTools(server, service) {
4133
4205
  annotations: {
4134
4206
  title: "Update Organisation Guardrail Defaults",
4135
4207
  readOnlyHint: false,
4136
- destructiveHint: false,
4137
4208
  idempotentHint: true,
4138
4209
  openWorldHint: true
4139
4210
  }
@@ -4402,31 +4473,68 @@ import { z as z15 } from "zod";
4402
4473
 
4403
4474
  // src/lib/limits.ts
4404
4475
  var PERIODIC_RESET_DEFAULT = "monthly";
4476
+ function hasUsageLimitInput(params) {
4477
+ return params.credit_limit !== void 0 || params.alert_threshold !== void 0 || params.type !== void 0 || params.periodic_reset !== void 0;
4478
+ }
4479
+ function copyDefinedUsageLimitFields(params, limits) {
4480
+ if (params.type !== void 0) {
4481
+ limits.type = params.type;
4482
+ }
4483
+ if (params.periodic_reset !== void 0) {
4484
+ limits.periodic_reset = params.periodic_reset;
4485
+ }
4486
+ if (params.credit_limit !== void 0) {
4487
+ limits.credit_limit = params.credit_limit;
4488
+ }
4489
+ if (params.alert_threshold !== void 0) {
4490
+ limits.alert_threshold = params.alert_threshold;
4491
+ }
4492
+ return limits;
4493
+ }
4405
4494
  function buildUsageLimits(params) {
4406
- if (params.credit_limit !== void 0 || params.alert_threshold !== void 0) {
4407
- const limits = {
4408
- type: params.type ?? "cost",
4409
- periodic_reset: params.periodic_reset ?? PERIODIC_RESET_DEFAULT
4410
- };
4411
- if (params.credit_limit !== void 0) {
4412
- limits.credit_limit = params.credit_limit;
4495
+ if (!hasUsageLimitInput(params)) {
4496
+ return void 0;
4497
+ }
4498
+ return copyDefinedUsageLimitFields(params, {
4499
+ type: "cost",
4500
+ periodic_reset: PERIODIC_RESET_DEFAULT
4501
+ });
4502
+ }
4503
+ function buildUsageLimitsUpdate(params) {
4504
+ if (!hasUsageLimitInput(params)) {
4505
+ return void 0;
4506
+ }
4507
+ return copyDefinedUsageLimitFields(params, {});
4508
+ }
4509
+ async function mergeUsageLimitsUpdate(supplied, readExisting) {
4510
+ if (supplied === void 0) {
4511
+ return void 0;
4512
+ }
4513
+ const existing = await readExisting();
4514
+ const base = existing ? {} : { type: "cost", periodic_reset: PERIODIC_RESET_DEFAULT };
4515
+ if (existing) {
4516
+ for (const key of [
4517
+ "type",
4518
+ "credit_limit",
4519
+ "alert_threshold",
4520
+ "periodic_reset",
4521
+ "periodic_reset_days"
4522
+ ]) {
4523
+ if (existing[key] !== void 0) {
4524
+ Object.assign(base, { [key]: existing[key] });
4525
+ }
4413
4526
  }
4414
- if (params.alert_threshold !== void 0) {
4415
- limits.alert_threshold = params.alert_threshold;
4527
+ if (supplied.periodic_reset !== void 0) {
4528
+ delete base.periodic_reset_days;
4529
+ } else if (base.periodic_reset_days !== void 0 && base.periodic_reset_days !== null) {
4530
+ delete base.periodic_reset;
4416
4531
  }
4417
- return limits;
4418
4532
  }
4419
- return void 0;
4533
+ return { ...base, ...supplied };
4420
4534
  }
4421
4535
  function buildRateLimitsRpm(rpmValue) {
4422
4536
  if (rpmValue !== void 0) {
4423
- return [
4424
- {
4425
- type: "requests",
4426
- unit: "rpm",
4427
- value: rpmValue
4428
- }
4429
- ];
4537
+ return buildRateLimits({ value: rpmValue, unit: "rpm" });
4430
4538
  }
4431
4539
  return void 0;
4432
4540
  }
@@ -5180,7 +5288,9 @@ var KEYS_TOOL_SCHEMAS = {
5180
5288
  alert_threshold: z16.coerce.number().min(0).max(100).optional().describe("New alert threshold percentage (0-100)"),
5181
5289
  rate_limit_rpm: z16.coerce.number().positive().optional().describe("New rate limit in requests per minute"),
5182
5290
  rate_limits: z16.array(apiKeyRateLimitSchema).nullable().optional().describe("Replacement request or token rate limits, or null to clear"),
5183
- reset_usage: z16.coerce.number().nonnegative().optional().describe("Set to a nonnegative acknowledgement value to reset usage"),
5291
+ reset_usage: z16.boolean().optional().describe(
5292
+ "Set to true to reset current usage; an exhausted key returns to active"
5293
+ ),
5184
5294
  default_config_id: z16.string().optional().describe("New default configuration ID"),
5185
5295
  default_metadata: z16.record(z16.string(), z16.string()).optional().describe("New default metadata key-value pairs"),
5186
5296
  default_allow_config_override: z16.boolean().optional().describe("Whether callers may override the key's default config"),
@@ -5227,6 +5337,7 @@ var createApiKeySchema = z16.object(KEYS_TOOL_SCHEMAS.createApiKey).superRefine(
5227
5337
  });
5228
5338
  function formatKeyUsageLimits(limits) {
5229
5339
  return limits ? {
5340
+ type: limits.type,
5230
5341
  credit_limit: limits.credit_limit,
5231
5342
  alert_threshold: limits.alert_threshold,
5232
5343
  periodic_reset: limits.periodic_reset
@@ -5372,18 +5483,22 @@ function registerKeysTools(server, service) {
5372
5483
  server.registerTool(
5373
5484
  "update_virtual_key",
5374
5485
  {
5375
- 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.",
5486
+ 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.",
5376
5487
  inputSchema: KEYS_TOOL_SCHEMAS.updateVirtualKey
5377
5488
  },
5378
5489
  async (params) => {
5490
+ const usageLimits = await mergeUsageLimitsUpdate(
5491
+ buildUsageLimitsUpdate({
5492
+ credit_limit: params.credit_limit,
5493
+ alert_threshold: params.alert_threshold
5494
+ }),
5495
+ async () => (await service.keys.getVirtualKey(params.slug)).usage_limits
5496
+ );
5379
5497
  const result = await service.keys.updateVirtualKey(params.slug, {
5380
5498
  name: params.name,
5381
5499
  key: params.key,
5382
5500
  note: params.note,
5383
- usage_limits: buildUsageLimits({
5384
- credit_limit: params.credit_limit,
5385
- alert_threshold: params.alert_threshold
5386
- }),
5501
+ usage_limits: usageLimits,
5387
5502
  rate_limits: buildRateLimitsRpm(params.rate_limit_rpm),
5388
5503
  deploymentConfig: params.deployment_configurations?.map(
5389
5504
  (configuration) => ({
@@ -5492,18 +5607,22 @@ function registerKeysTools(server, service) {
5492
5607
  server.registerTool(
5493
5608
  "update_api_key",
5494
5609
  {
5495
- 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.",
5610
+ 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.",
5496
5611
  inputSchema: KEYS_TOOL_SCHEMAS.updateApiKey
5497
5612
  },
5498
5613
  async (params) => {
5614
+ const usageLimits = await mergeUsageLimitsUpdate(
5615
+ buildUsageLimitsUpdate({
5616
+ credit_limit: params.credit_limit,
5617
+ alert_threshold: params.alert_threshold
5618
+ }),
5619
+ async () => (await service.keys.getApiKey(params.id)).usage_limits
5620
+ );
5499
5621
  const result = await service.keys.updateApiKey(params.id, {
5500
5622
  name: params.name,
5501
5623
  description: params.description,
5502
5624
  scopes: params.scopes,
5503
- usage_limits: buildUsageLimits({
5504
- credit_limit: params.credit_limit,
5505
- alert_threshold: params.alert_threshold
5506
- }),
5625
+ usage_limits: usageLimits,
5507
5626
  rate_limits: params.rate_limits === void 0 ? buildRateLimitsRpm(params.rate_limit_rpm) : params.rate_limits,
5508
5627
  ...params.reset_usage !== void 0 ? { reset_usage: params.reset_usage } : {},
5509
5628
  defaults: params.default_config_id !== void 0 || params.default_metadata !== void 0 || params.default_allow_config_override !== void 0 ? {
@@ -6377,7 +6496,10 @@ var MCP_INTEGRATIONS_TOOL_SCHEMAS = {
6377
6496
  "Additional documented or forward-compatible configuration fields. For headers auth, configurations.custom_headers is a string-to-string header map."
6378
6497
  ),
6379
6498
  workspace_id: z20.string().optional().describe(
6380
- "Workspace ID \u2014 required when using organization admin API keys"
6499
+ "Workspace ID; set it to create the integration at workspace level. With an organisation admin key, give this or organisation_id."
6500
+ ),
6501
+ organisation_id: z20.string().optional().describe(
6502
+ "Organisation ID; required with an organisation admin API key when workspace_id is omitted"
6381
6503
  ),
6382
6504
  secret_mappings: mcpSecretMappingsSchema.optional().describe(
6383
6505
  "Runtime Secret Reference mappings; every configurations.<field> target must be unique"
@@ -6415,7 +6537,8 @@ var MCP_INTEGRATIONS_TOOL_SCHEMAS = {
6415
6537
  id: z20.string().describe("The MCP integration ID or slug")
6416
6538
  },
6417
6539
  listMcpIntegrationCapabilities: {
6418
- id: z20.string().describe("The MCP integration ID or slug")
6540
+ id: z20.string().describe("The MCP integration ID or slug"),
6541
+ type: z20.enum(["tool", "prompt", "resource", "resource_template"]).optional().describe("Only return capabilities of this type")
6419
6542
  },
6420
6543
  updateMcpIntegrationCapabilities: {
6421
6544
  id: z20.string().describe("The MCP integration ID or slug"),
@@ -6437,7 +6560,15 @@ var MCP_INTEGRATIONS_TOOL_SCHEMAS = {
6437
6560
  id: z20.string().describe("Workspace ID"),
6438
6561
  enabled: z20.boolean().describe("Whether workspace has access")
6439
6562
  })
6440
- ).min(1).describe("Array of workspace access updates")
6563
+ ).describe(
6564
+ "Array of workspace access updates; may be empty when only changing global_workspace_access"
6565
+ ),
6566
+ global_workspace_access: z20.object({
6567
+ enabled: z20.boolean().describe("Whether every workspace gets access by default")
6568
+ }).optional().describe("Organisation-wide workspace access default"),
6569
+ override_existing_workspace_access: z20.boolean().optional().describe(
6570
+ "When true, global_workspace_access replaces existing per-workspace settings"
6571
+ )
6441
6572
  }
6442
6573
  };
6443
6574
  var createMcpIntegrationSchema = z20.object(MCP_INTEGRATIONS_TOOL_SCHEMAS.createMcpIntegration).superRefine((value, ctx) => {
@@ -6640,7 +6771,12 @@ function registerMcpIntegrationsTools(server, service) {
6640
6771
  inputSchema: MCP_INTEGRATIONS_TOOL_SCHEMAS.listMcpIntegrationCapabilities
6641
6772
  },
6642
6773
  async (params) => {
6643
- const result = await service.mcpIntegrations.listMcpIntegrationCapabilities(params.id);
6774
+ const result = await service.mcpIntegrations.listMcpIntegrationCapabilities(
6775
+ params.id,
6776
+ {
6777
+ type: params.type
6778
+ }
6779
+ );
6644
6780
  return jsonResult({
6645
6781
  total: result.total,
6646
6782
  capabilities: result.data
@@ -6654,7 +6790,6 @@ function registerMcpIntegrationsTools(server, service) {
6654
6790
  inputSchema: MCP_INTEGRATIONS_TOOL_SCHEMAS.updateMcpIntegrationCapabilities,
6655
6791
  annotations: {
6656
6792
  readOnlyHint: false,
6657
- destructiveHint: false,
6658
6793
  idempotentHint: true,
6659
6794
  openWorldHint: false
6660
6795
  }
@@ -6696,14 +6831,17 @@ function registerMcpIntegrationsTools(server, service) {
6696
6831
  inputSchema: MCP_INTEGRATIONS_TOOL_SCHEMAS.updateMcpIntegrationWorkspaces,
6697
6832
  annotations: {
6698
6833
  readOnlyHint: false,
6699
- destructiveHint: false,
6700
6834
  idempotentHint: true,
6701
6835
  openWorldHint: false
6702
6836
  }
6703
6837
  },
6704
6838
  async (params) => {
6705
6839
  await service.mcpIntegrations.updateMcpIntegrationWorkspaces(params.id, {
6706
- workspaces: params.workspaces
6840
+ workspaces: params.workspaces,
6841
+ ...params.global_workspace_access !== void 0 ? { global_workspace_access: params.global_workspace_access } : {},
6842
+ ...params.override_existing_workspace_access !== void 0 ? {
6843
+ override_existing_workspace_access: params.override_existing_workspace_access
6844
+ } : {}
6707
6845
  });
6708
6846
  return jsonResult({
6709
6847
  message: `Successfully updated workspace access for MCP integration "${params.id}"`,
@@ -6720,7 +6858,9 @@ var MCP_SERVERS_TOOL_SCHEMAS = {
6720
6858
  tags: resourceTagsSchema.optional().describe("Match resources carrying all supplied tags"),
6721
6859
  current_page: CurrentPageSchema,
6722
6860
  page_size: PageSizeSchema.describe("Number of results per page (max 100)"),
6723
- workspace_id: z21.string().optional().describe("Filter by workspace ID")
6861
+ workspace_id: z21.string().optional().describe("Filter by workspace ID"),
6862
+ id: z21.string().optional().describe("Filter by MCP server ID, or several IDs separated by commas"),
6863
+ search: z21.string().max(255).optional().describe("Search MCP servers (up to 255 characters)")
6724
6864
  },
6725
6865
  createMcpServer: {
6726
6866
  tags: resourceTagsSchema.nullable().optional().describe(
@@ -6729,7 +6869,10 @@ var MCP_SERVERS_TOOL_SCHEMAS = {
6729
6869
  name: z21.string().describe("Display name for the MCP server"),
6730
6870
  mcp_integration_id: z21.string().describe("ID or slug of the MCP integration this server belongs to"),
6731
6871
  slug: z21.string().optional().describe("Custom slug. Auto-generated if omitted"),
6732
- description: z21.string().optional().describe("Description of the MCP server")
6872
+ description: z21.string().optional().describe("Description of the MCP server"),
6873
+ workspace_id: z21.string().optional().describe(
6874
+ "Workspace ID or slug; required with an organisation admin API key"
6875
+ )
6733
6876
  },
6734
6877
  getMcpServer: {
6735
6878
  id: z21.string().describe("The MCP server ID or slug to retrieve")
@@ -6751,7 +6894,8 @@ var MCP_SERVERS_TOOL_SCHEMAS = {
6751
6894
  listMcpServerCapabilities: {
6752
6895
  id: z21.string().describe("The MCP server ID or slug"),
6753
6896
  current_page: CurrentPageSchema,
6754
- page_size: PageSizeSchema.describe("Number of results per page (max 100)")
6897
+ page_size: PageSizeSchema.describe("Number of results per page (max 100)"),
6898
+ type: z21.enum(["tool", "prompt", "resource", "resource_template"]).optional().describe("Only return capabilities of this type")
6755
6899
  },
6756
6900
  updateMcpServerCapabilities: {
6757
6901
  id: z21.string().describe("The MCP server ID or slug"),
@@ -6766,7 +6910,8 @@ var MCP_SERVERS_TOOL_SCHEMAS = {
6766
6910
  listMcpServerUserAccess: {
6767
6911
  id: z21.string().describe("The MCP server ID or slug"),
6768
6912
  current_page: CurrentPageSchema,
6769
- page_size: PageSizeSchema.describe("Number of results per page (max 100)")
6913
+ page_size: PageSizeSchema.describe("Number of results per page (max 100)"),
6914
+ search: z21.string().optional().describe("Search by user name or email")
6770
6915
  },
6771
6916
  updateMcpServerUserAccess: {
6772
6917
  id: z21.string().describe("The MCP server ID or slug"),
@@ -6775,7 +6920,10 @@ var MCP_SERVERS_TOOL_SCHEMAS = {
6775
6920
  user_id: z21.string().describe("User ID"),
6776
6921
  enabled: z21.boolean().describe("Whether user has access")
6777
6922
  })
6778
- ).min(1).describe("Array of user access updates")
6923
+ ).min(1).optional().describe("Array of user access updates"),
6924
+ default_user_access: z21.enum(["allow", "deny"]).optional().describe(
6925
+ "Server default for users without an explicit override. Provide this, users, or both"
6926
+ )
6779
6927
  },
6780
6928
  listMcpServerConnections: {
6781
6929
  id: z21.string().describe("MCP server ID or slug whose connections to list"),
@@ -6802,6 +6950,13 @@ var MCP_SERVERS_TOOL_SCHEMAS = {
6802
6950
  )
6803
6951
  }
6804
6952
  };
6953
+ var updateMcpServerUserAccessSchema = z21.object(MCP_SERVERS_TOOL_SCHEMAS.updateMcpServerUserAccess).refine(
6954
+ (value) => value.users !== void 0 || value.default_user_access !== void 0,
6955
+ {
6956
+ message: "Provide users, default_user_access, or both",
6957
+ path: ["users"]
6958
+ }
6959
+ );
6805
6960
  function formatMcpServer(server) {
6806
6961
  return {
6807
6962
  id: server.id,
@@ -6982,7 +7137,8 @@ function registerMcpServersTools(server, service) {
6982
7137
  params.id,
6983
7138
  {
6984
7139
  current_page: params.current_page,
6985
- page_size: params.page_size
7140
+ page_size: params.page_size,
7141
+ type: params.type
6986
7142
  }
6987
7143
  );
6988
7144
  return jsonResult({
@@ -7019,7 +7175,8 @@ function registerMcpServersTools(server, service) {
7019
7175
  params.id,
7020
7176
  {
7021
7177
  current_page: params.current_page,
7022
- page_size: params.page_size
7178
+ page_size: params.page_size,
7179
+ search: params.search
7023
7180
  }
7024
7181
  );
7025
7182
  return jsonResult({
@@ -7033,12 +7190,14 @@ function registerMcpServersTools(server, service) {
7033
7190
  server.registerTool(
7034
7191
  "update_mcp_server_user_access",
7035
7192
  {
7036
- 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.",
7193
+ 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.",
7037
7194
  inputSchema: MCP_SERVERS_TOOL_SCHEMAS.updateMcpServerUserAccess
7038
7195
  },
7039
- async (params) => {
7196
+ async (rawParams) => {
7197
+ const params = updateMcpServerUserAccessSchema.parse(rawParams);
7040
7198
  await service.mcpServers.updateMcpServerUserAccess(params.id, {
7041
- user_access: params.users
7199
+ ...params.users !== void 0 ? { user_access: params.users } : {},
7200
+ ...params.default_user_access !== void 0 ? { default_user_access: params.default_user_access } : {}
7042
7201
  });
7043
7202
  return jsonResult({
7044
7203
  message: `Successfully updated user access for MCP server "${params.id}"`,
@@ -7737,7 +7896,7 @@ function registerPromptsTools(server, service) {
7737
7896
  server.registerTool(
7738
7897
  "run_prompt_completion",
7739
7898
  {
7740
- 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.",
7899
+ 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.",
7741
7900
  inputSchema: PROMPTS_TOOL_SCHEMAS.runPromptCompletion
7742
7901
  },
7743
7902
  async (params) => {
@@ -7755,6 +7914,9 @@ function registerPromptsTools(server, service) {
7755
7914
  id: result.id,
7756
7915
  model: result.model,
7757
7916
  response: choice?.message?.content ?? null,
7917
+ // Returned as data only. The server never executes a tool call.
7918
+ ...choice?.message?.tool_calls?.length ? { tool_calls: choice.message.tool_calls } : {},
7919
+ ...choice?.message?.function_call ? { function_call: choice.message.function_call } : {},
7758
7920
  finish_reason: choice?.finish_reason ?? null,
7759
7921
  usage: result.usage ? {
7760
7922
  prompt_tokens: result.usage.prompt_tokens,
@@ -7937,14 +8099,16 @@ var PROVIDERS_TOOL_SCHEMAS = {
7937
8099
  credit_limit: z24.coerce.number().positive().optional().describe("New credit limit for usage"),
7938
8100
  alert_threshold: z24.coerce.number().min(0).max(100).optional().describe("New alert threshold percentage (0-100)"),
7939
8101
  usage_limit_type: z24.enum(["cost", "tokens"]).optional().describe(
7940
- "Type of usage limit: 'cost' (monetary) or 'tokens' (token count). Defaults to 'cost'."
8102
+ "Usage limit type: 'cost' or 'tokens'. If omitted, preserves the existing type; defaults to 'cost' when no limits exist."
7941
8103
  ),
7942
8104
  periodic_reset: z24.enum(["monthly", "weekly"]).optional().describe(
7943
- "Period for resetting usage limits: 'monthly' or 'weekly'. Defaults to 'monthly'."
8105
+ "Reset period: 'monthly' or 'weekly'. If omitted, preserves the existing cadence, including custom reset days; defaults to 'monthly' when no limits exist."
8106
+ ),
8107
+ rate_limit_value: z24.coerce.number().positive().optional().describe(
8108
+ "New rate limit value. Must be provided together with rate_limit_unit."
7944
8109
  ),
7945
- rate_limit_value: z24.coerce.number().positive().optional().describe("New rate limit value"),
7946
8110
  rate_limit_unit: z24.enum(["rpm", "rph", "rpd"]).optional().describe(
7947
- "Rate limit unit: 'rpm' (requests per minute), 'rph' (requests per hour), or 'rpd' (requests per day)"
8111
+ "Rate limit unit: 'rpm' (requests per minute), 'rph' (requests per hour), or 'rpd' (requests per day). Must be provided together with rate_limit_value."
7948
8112
  ),
7949
8113
  expires_at: z24.string().optional().describe("New expiration date in ISO 8601 format"),
7950
8114
  reset_usage: z24.boolean().optional().describe("Set to true to reset accumulated usage metrics")
@@ -7954,6 +8118,18 @@ var PROVIDERS_TOOL_SCHEMAS = {
7954
8118
  workspace_id: z24.string().optional().describe("Workspace ID - required when using organization admin keys")
7955
8119
  }
7956
8120
  };
8121
+ var RATE_LIMIT_PAIR_MESSAGE = "rate_limit_value and rate_limit_unit must be provided together";
8122
+ function hasCompleteRateLimitPair(value) {
8123
+ return value.rate_limit_value === void 0 === (value.rate_limit_unit === void 0);
8124
+ }
8125
+ var createProviderSchema = z24.object(PROVIDERS_TOOL_SCHEMAS.createProvider).refine(hasCompleteRateLimitPair, {
8126
+ path: ["rate_limit_unit"],
8127
+ message: RATE_LIMIT_PAIR_MESSAGE
8128
+ });
8129
+ var updateProviderSchema = z24.object(PROVIDERS_TOOL_SCHEMAS.updateProvider).refine(hasCompleteRateLimitPair, {
8130
+ path: ["rate_limit_unit"],
8131
+ message: RATE_LIMIT_PAIR_MESSAGE
8132
+ });
7957
8133
  function registerProvidersTools(server, service) {
7958
8134
  server.registerTool(
7959
8135
  "list_providers",
@@ -7976,6 +8152,7 @@ function registerProvidersTools(server, service) {
7976
8152
  status: provider.status,
7977
8153
  note: provider.note,
7978
8154
  usage_limits: provider.usage_limits ? {
8155
+ type: provider.usage_limits.type,
7979
8156
  credit_limit: provider.usage_limits.credit_limit,
7980
8157
  alert_threshold: provider.usage_limits.alert_threshold,
7981
8158
  periodic_reset: provider.usage_limits.periodic_reset
@@ -7998,7 +8175,8 @@ function registerProvidersTools(server, service) {
7998
8175
  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.",
7999
8176
  inputSchema: PROVIDERS_TOOL_SCHEMAS.createProvider
8000
8177
  },
8001
- async (params) => {
8178
+ async (rawParams) => {
8179
+ const params = createProviderSchema.parse(rawParams);
8002
8180
  const result = await service.providers.createProvider({
8003
8181
  name: params.name,
8004
8182
  integration_id: params.integration_id,
@@ -8042,6 +8220,7 @@ function registerProvidersTools(server, service) {
8042
8220
  status: provider.status,
8043
8221
  note: provider.note,
8044
8222
  usage_limits: provider.usage_limits ? {
8223
+ type: provider.usage_limits.type,
8045
8224
  credit_limit: provider.usage_limits.credit_limit,
8046
8225
  alert_threshold: provider.usage_limits.alert_threshold,
8047
8226
  periodic_reset: provider.usage_limits.periodic_reset
@@ -8060,21 +8239,29 @@ function registerProvidersTools(server, service) {
8060
8239
  server.registerTool(
8061
8240
  "update_provider",
8062
8241
  {
8063
- 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.",
8242
+ 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.",
8064
8243
  inputSchema: PROVIDERS_TOOL_SCHEMAS.updateProvider
8065
8244
  },
8066
- async (params) => {
8245
+ async (rawParams) => {
8246
+ const params = updateProviderSchema.parse(rawParams);
8247
+ const usageLimits = await mergeUsageLimitsUpdate(
8248
+ buildUsageLimitsUpdate({
8249
+ credit_limit: params.credit_limit,
8250
+ alert_threshold: params.alert_threshold,
8251
+ type: params.usage_limit_type,
8252
+ periodic_reset: params.periodic_reset
8253
+ }),
8254
+ async () => (await service.providers.getProvider(
8255
+ params.slug,
8256
+ params.workspace_id
8257
+ )).usage_limits
8258
+ );
8067
8259
  const result = await service.providers.updateProvider(
8068
8260
  params.slug,
8069
8261
  {
8070
8262
  name: params.name,
8071
8263
  note: params.note,
8072
- usage_limits: buildUsageLimits({
8073
- credit_limit: params.credit_limit,
8074
- alert_threshold: params.alert_threshold,
8075
- type: params.usage_limit_type,
8076
- periodic_reset: params.periodic_reset
8077
- }),
8264
+ usage_limits: usageLimits,
8078
8265
  rate_limits: params.rate_limit_value !== void 0 && params.rate_limit_unit !== void 0 ? buildRateLimits({
8079
8266
  value: params.rate_limit_value,
8080
8267
  unit: params.rate_limit_unit
@@ -8963,6 +9150,14 @@ function formatWorkspaceDefaults(defaults) {
8963
9150
  metadata: defaults.metadata
8964
9151
  };
8965
9152
  }
9153
+ function formatWorkspaceFlagsAndLimits(workspace) {
9154
+ return {
9155
+ is_default: workspace.is_default ?? workspace.defaults?.is_default,
9156
+ defaults: formatWorkspaceDefaults(workspace.defaults),
9157
+ usage_limits: workspace.usage_limits ?? null,
9158
+ rate_limits: workspace.rate_limits ?? null
9159
+ };
9160
+ }
8966
9161
  function formatWorkspaceSummary(workspace) {
8967
9162
  return {
8968
9163
  id: workspace.id,
@@ -8971,7 +9166,7 @@ function formatWorkspaceSummary(workspace) {
8971
9166
  description: workspace.description,
8972
9167
  created_at: workspace.created_at,
8973
9168
  last_updated_at: workspace.last_updated_at,
8974
- defaults: formatWorkspaceDefaults(workspace.defaults)
9169
+ ...formatWorkspaceFlagsAndLimits(workspace)
8975
9170
  };
8976
9171
  }
8977
9172
  function formatWorkspaceMember(user) {
@@ -8993,7 +9188,7 @@ function formatWorkspaceDetail(workspace) {
8993
9188
  description: workspace.description,
8994
9189
  created_at: workspace.created_at,
8995
9190
  last_updated_at: workspace.last_updated_at,
8996
- defaults: formatWorkspaceDefaults(workspace.defaults),
9191
+ ...formatWorkspaceFlagsAndLimits(workspace),
8997
9192
  users: workspace.users.map(formatWorkspaceMember)
8998
9193
  };
8999
9194
  }
@@ -9340,7 +9535,9 @@ var DESTRUCTIVE_TOOL_PREFIXES = [
9340
9535
  "delete_",
9341
9536
  "remove_",
9342
9537
  "cancel_",
9343
- "reset_"
9538
+ "reset_",
9539
+ "update_",
9540
+ "archive_"
9344
9541
  ];
9345
9542
  var ENTERPRISE_GATED_TOOL_NAMES = /* @__PURE__ */ new Set([
9346
9543
  "get_cost_analytics",
@@ -9473,12 +9670,12 @@ function getToolErrorMessage(error) {
9473
9670
  return String(error);
9474
9671
  }
9475
9672
  var STANDARD_TOOL_OUTPUT_SCHEMA = {
9476
- ok: z29.boolean().describe("Whether the tool call succeeded and returned structured data"),
9477
- data: z29.unknown().optional().describe("Structured success payload when ok is true"),
9673
+ ok: z29.boolean().describe("Call succeeded"),
9674
+ data: z29.unknown().optional().describe("Success payload"),
9478
9675
  error: z29.object({
9479
- message: z29.string().describe("Human-readable error message"),
9480
- details: z29.unknown().optional().describe("Optional structured error details")
9481
- }).optional().describe("Structured error payload when ok is false")
9676
+ message: z29.string().describe("Error message"),
9677
+ details: z29.unknown().optional().describe("Extra error details")
9678
+ }).optional().describe("Failure details")
9482
9679
  };
9483
9680
  var TOOL_SUCCESS_DATA_SCHEMAS = {
9484
9681
  create_access_policy: CreateAccessPolicyResponseSchema,
@@ -9496,7 +9693,10 @@ var TOOL_SUCCESS_DATA_SCHEMAS = {
9496
9693
  warning: z29.string().describe("Required handling guidance for the one-time secret"),
9497
9694
  id: z29.string().uuid().describe("Rotated API key UUID"),
9498
9695
  key: z29.string().describe("New API key secret, returned only once"),
9499
- key_transition_expires_at: z29.iso.datetime().describe("Time when the previous key stops working")
9696
+ // Offsets such as +00:00 are valid RFC 3339, and the field is optional in
9697
+ // the spec. A strict schema here fails after the rotation already ran,
9698
+ // which would drop the one-time secret.
9699
+ key_transition_expires_at: z29.iso.datetime({ offset: true }).optional().describe("Time when the previous key stops working")
9500
9700
  }),
9501
9701
  create_secret_reference: z29.object({
9502
9702
  message: z29.string().describe("Creation confirmation"),
@@ -9513,9 +9713,9 @@ var TOOL_SUCCESS_DATA_SCHEMAS = {
9513
9713
  manager_type: SecretManagerTypeSchema.describe(
9514
9714
  "External secret manager type"
9515
9715
  ),
9516
- status: z29.literal("ACTIVE").describe("Current reference status"),
9517
- created_at: z29.iso.datetime().describe("ISO 8601 creation timestamp"),
9518
- last_updated_at: z29.iso.datetime().describe("ISO 8601 last-update timestamp")
9716
+ status: z29.string().describe("Current reference status, ACTIVE for usable references"),
9717
+ created_at: z29.iso.datetime({ offset: true }).describe("ISO 8601 creation timestamp"),
9718
+ last_updated_at: z29.iso.datetime({ offset: true }).describe("ISO 8601 last-update timestamp")
9519
9719
  })
9520
9720
  ).describe(
9521
9721
  "Current page of Secret References without authentication values"
@@ -9534,10 +9734,10 @@ var TOOL_SUCCESS_DATA_SCHEMAS = {
9534
9734
  secret_key: z29.string().nullable().describe("Selected key within a structured secret"),
9535
9735
  allow_all_workspaces: z29.boolean().describe("Whether all workspaces may use the reference"),
9536
9736
  tags: z29.record(z29.string(), z29.string()).nullable().describe("String metadata tags"),
9537
- status: z29.literal("ACTIVE").describe("Current reference status"),
9737
+ status: z29.string().describe("Current reference status"),
9538
9738
  created_by: z29.string().describe("Creator identifier"),
9539
- created_at: z29.iso.datetime().describe("ISO 8601 creation timestamp"),
9540
- last_updated_at: z29.iso.datetime().describe("ISO 8601 last-update timestamp"),
9739
+ created_at: z29.iso.datetime({ offset: true }).describe("ISO 8601 creation timestamp"),
9740
+ last_updated_at: z29.iso.datetime({ offset: true }).describe("ISO 8601 last-update timestamp"),
9541
9741
  auth_config: z29.record(z29.string(), z29.unknown()).describe("Authentication configuration with sensitive values redacted"),
9542
9742
  object: z29.literal("secret-reference").describe("Portkey object type")
9543
9743
  }),
@@ -9555,7 +9755,7 @@ function getToolOutputSchema(toolName) {
9555
9755
  if (!dataSchema) return STANDARD_TOOL_OUTPUT_SCHEMA;
9556
9756
  return {
9557
9757
  ...STANDARD_TOOL_OUTPUT_SCHEMA,
9558
- data: dataSchema.optional().describe("Structured success payload when ok is true")
9758
+ data: dataSchema.optional().describe("Success payload")
9559
9759
  };
9560
9760
  }
9561
9761
  function isStandardToolEnvelope(value) {
@@ -9617,10 +9817,31 @@ function normalizeToolResult(result) {
9617
9817
  structuredContent: envelope
9618
9818
  };
9619
9819
  }
9820
+ function measureToolResultBytes(result) {
9821
+ const text = getFirstTextContent(result) ?? "";
9822
+ return Buffer.byteLength(JSON.stringify(text)) + Buffer.byteLength(text);
9823
+ }
9824
+ function enforceToolResultLimit(toolName, result) {
9825
+ const limit = getMaxToolResultBytes();
9826
+ const bytes = measureToolResultBytes(result);
9827
+ if (bytes <= limit) return result;
9828
+ return normalizeToolResult({
9829
+ content: [
9830
+ {
9831
+ type: "text",
9832
+ 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.`
9833
+ }
9834
+ ],
9835
+ isError: true
9836
+ });
9837
+ }
9620
9838
  function wrapToolCallback(toolName, callback) {
9621
9839
  return async (...args) => {
9622
9840
  try {
9623
- return normalizeToolResult(await callback(...args));
9841
+ return enforceToolResultLimit(
9842
+ toolName,
9843
+ normalizeToolResult(await callback(...args))
9844
+ );
9624
9845
  } catch (error) {
9625
9846
  const message = getToolErrorMessage(error);
9626
9847
  const isValidationError = error instanceof z29.ZodError;
@@ -9629,23 +9850,64 @@ function wrapToolCallback(toolName, callback) {
9629
9850
  error: message,
9630
9851
  metadata: { toolName }
9631
9852
  });
9632
- return normalizeToolResult({
9633
- content: [{ type: "text", text }],
9634
- isError: true
9635
- });
9853
+ return enforceToolResultLimit(
9854
+ toolName,
9855
+ normalizeToolResult({
9856
+ content: [{ type: "text", text }],
9857
+ isError: true
9858
+ })
9859
+ );
9636
9860
  }
9637
9861
  };
9638
9862
  }
9639
9863
  var registrationSchemas = /* @__PURE__ */ new WeakMap();
9864
+ var outputSchemasByTool = /* @__PURE__ */ new Map();
9865
+ var jsonSchemaConversions = 0;
9866
+ function memoizeJsonSchemaConversion(schema) {
9867
+ const standard = schema["~standard"];
9868
+ const converters = standard?.jsonSchema;
9869
+ if (!standard || !converters) return schema;
9870
+ const memoize = (direction) => {
9871
+ const convert = converters[direction];
9872
+ if (!convert) return void 0;
9873
+ const results = /* @__PURE__ */ new Map();
9874
+ return (options) => {
9875
+ const key = JSON.stringify(options ?? null);
9876
+ let result = results.get(key);
9877
+ if (!result) {
9878
+ jsonSchemaConversions += 1;
9879
+ result = convert(options);
9880
+ results.set(key, result);
9881
+ }
9882
+ return result;
9883
+ };
9884
+ };
9885
+ return Object.create(schema, {
9886
+ "~standard": {
9887
+ value: {
9888
+ ...standard,
9889
+ jsonSchema: { input: memoize("input"), output: memoize("output") }
9890
+ }
9891
+ }
9892
+ });
9893
+ }
9640
9894
  function normalizeRegistrationSchema(schema) {
9641
- if (!isRecord(schema) || "~standard" in schema) return schema;
9642
- let normalized = registrationSchemas.get(schema);
9643
- if (!normalized) {
9644
- normalized = z29.object(schema);
9645
- registrationSchemas.set(schema, normalized);
9646
- }
9895
+ if (!isRecord(schema)) return schema;
9896
+ if (registrationSchemas.has(schema)) return registrationSchemas.get(schema);
9897
+ const normalized = memoizeJsonSchemaConversion(
9898
+ "~standard" in schema ? schema : z29.object(schema)
9899
+ );
9900
+ registrationSchemas.set(schema, normalized);
9647
9901
  return normalized;
9648
9902
  }
9903
+ function getRegistrationOutputSchema(toolName) {
9904
+ let schema = outputSchemasByTool.get(toolName);
9905
+ if (!schema) {
9906
+ schema = getToolOutputSchema(toolName);
9907
+ outputSchemasByTool.set(toolName, schema);
9908
+ }
9909
+ return schema;
9910
+ }
9649
9911
  function createSafeToolServer(server) {
9650
9912
  const originalRegisterTool = server.registerTool.bind(server);
9651
9913
  const safeServer = Object.create(server);
@@ -9661,7 +9923,7 @@ function createSafeToolServer(server) {
9661
9923
  ...description === void 0 ? {} : { description },
9662
9924
  inputSchema: normalizeRegistrationSchema(config.inputSchema),
9663
9925
  outputSchema: normalizeRegistrationSchema(
9664
- config.outputSchema ?? getToolOutputSchema(name)
9926
+ config.outputSchema ?? getRegistrationOutputSchema(name)
9665
9927
  ),
9666
9928
  annotations: {
9667
9929
  ...inferToolAnnotations(name),
@@ -9789,9 +10051,9 @@ function getHttpAuthConfigFromEnv() {
9789
10051
  `MCP_AUTH_MODE=clerk configuration error (${issues.join("; ")})`
9790
10052
  );
9791
10053
  }
9792
- if (!allowedSubjects && !allowedOrganizationIds && !allowedRoles && !requiredPermissions) {
10054
+ if (!allowedSubjects && !allowedOrganizationIds) {
9793
10055
  throw new Error(
9794
- "MCP_AUTH_MODE=clerk requires an explicit authorization policy. Set at least one of CLERK_ALLOWED_SUBJECTS, CLERK_ALLOWED_ORGANIZATION_IDS, CLERK_ALLOWED_ROLES, or CLERK_REQUIRED_PERMISSIONS."
10056
+ "MCP_AUTH_MODE=clerk requires an identity-bound authorization policy. Set CLERK_ALLOWED_SUBJECTS or CLERK_ALLOWED_ORGANIZATION_IDS. CLERK_ALLOWED_ROLES and CLERK_REQUIRED_PERMISSIONS can narrow the policy but can't authorize on their own."
9795
10057
  );
9796
10058
  }
9797
10059
  }
@@ -9854,25 +10116,76 @@ function asStringArray(value) {
9854
10116
  function unique(values) {
9855
10117
  return [...new Set(values)];
9856
10118
  }
10119
+ function decodeClerkV2Permissions(features, per, fpm) {
10120
+ if (typeof features !== "string" || typeof per !== "string" || typeof fpm !== "string" || !per || !fpm) {
10121
+ return [];
10122
+ }
10123
+ const orgFeatures = [];
10124
+ for (const part of features.split(",")) {
10125
+ const entry = part.trim();
10126
+ const colon = entry.indexOf(":");
10127
+ if (colon === -1) {
10128
+ return [];
10129
+ }
10130
+ const scope = entry.slice(0, colon);
10131
+ const feature = entry.slice(colon + 1);
10132
+ if (scope === "o" || scope === "ou" || scope === "uo") {
10133
+ orgFeatures.push(feature);
10134
+ }
10135
+ }
10136
+ const permissionNames = per.split(",").map((name) => name.trim());
10137
+ const masks = fpm.split(",").map((mask) => mask.trim());
10138
+ const granted = [];
10139
+ for (const [featureIndex, feature] of orgFeatures.entries()) {
10140
+ const rawMask = masks[featureIndex];
10141
+ if (!feature || rawMask === void 0 || !/^\d+$/.test(rawMask)) {
10142
+ continue;
10143
+ }
10144
+ const mask = BigInt(rawMask);
10145
+ for (const [permissionIndex, name] of permissionNames.entries()) {
10146
+ if (name && mask >> BigInt(permissionIndex) & 1n) {
10147
+ granted.push(`org:${feature}:${name}`);
10148
+ }
10149
+ }
10150
+ }
10151
+ return granted;
10152
+ }
9857
10153
  function authorizeClerkClaims(payload, config) {
9858
10154
  const subject = asString(payload.sub);
9859
10155
  if (!subject) {
9860
10156
  throw new ClerkAuthorizationError("Clerk token is missing a subject");
9861
10157
  }
9862
- const organization = typeof payload.o === "object" && payload.o !== null ? payload.o : void 0;
9863
- const organizationId = asString(payload.org_id) ?? asString(organization?.id);
9864
- const roles = unique(
9865
- [
9866
- asString(payload.org_role),
9867
- asString(organization?.rol),
10158
+ let organizationId;
10159
+ let roles;
10160
+ let permissions;
10161
+ if (payload.v === 2) {
10162
+ const organization = typeof payload.o === "object" && payload.o !== null ? payload.o : void 0;
10163
+ organizationId = asString(organization?.id);
10164
+ const role = asString(organization?.rol);
10165
+ roles = unique([
10166
+ ...role ? [`org:${role}`] : [],
9868
10167
  ...asStringArray(payload.roles)
9869
- ].filter((role) => Boolean(role))
9870
- );
9871
- const permissions = unique([
9872
- ...asStringArray(payload.org_permissions),
9873
- ...asStringArray(organization?.per),
9874
- ...asStringArray(payload.permissions)
9875
- ]);
10168
+ ]);
10169
+ permissions = unique([
10170
+ ...decodeClerkV2Permissions(
10171
+ payload.fea,
10172
+ organization?.per,
10173
+ organization?.fpm
10174
+ ),
10175
+ ...asStringArray(payload.permissions)
10176
+ ]);
10177
+ } else {
10178
+ organizationId = asString(payload.org_id);
10179
+ roles = unique(
10180
+ [asString(payload.org_role), ...asStringArray(payload.roles)].filter(
10181
+ (role) => Boolean(role)
10182
+ )
10183
+ );
10184
+ permissions = unique([
10185
+ ...asStringArray(payload.org_permissions),
10186
+ ...asStringArray(payload.permissions)
10187
+ ]);
10188
+ }
9876
10189
  if (config.allowedSubjects && !config.allowedSubjects.includes(subject)) {
9877
10190
  throw new ClerkAuthorizationError("Clerk subject is not authorized");
9878
10191
  }
@@ -9918,6 +10231,9 @@ async function verifyClerkToken(token, config) {
9918
10231
  audience: config.audience,
9919
10232
  clockTolerance: "5s"
9920
10233
  });
10234
+ if (payload.sts === "pending") {
10235
+ throw new Error("Clerk session is pending");
10236
+ }
9921
10237
  return authorizeClerkClaims(payload, config);
9922
10238
  }
9923
10239
  async function mcpAuthMiddleware(req, res, next) {
@@ -10888,13 +11204,18 @@ function createReadyHandler(deps) {
10888
11204
  });
10889
11205
  return;
10890
11206
  } catch (error) {
11207
+ Logger.error("Portkey readiness check failed", {
11208
+ metadata: {
11209
+ error: error instanceof Error ? error.message : "Unknown error"
11210
+ }
11211
+ });
10891
11212
  res.status(503).json({
10892
11213
  status: "not_ready",
10893
11214
  activeRequests,
10894
11215
  sessionMode: "stateless",
10895
11216
  portkey: {
10896
11217
  status: "error",
10897
- error: error instanceof Error ? error.message : "Unknown error"
11218
+ error: "Upstream readiness check failed"
10898
11219
  },
10899
11220
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
10900
11221
  });
@@ -11082,6 +11403,8 @@ function createHttpAppRuntime() {
11082
11403
  const config = getServerConfig();
11083
11404
  const authConfig = getHttpAuthConfig();
11084
11405
  assertSafeHttpAuthConfig(authConfig);
11406
+ parseConfiguredToolDomains();
11407
+ assertByteLimitsConfigured();
11085
11408
  const readyCheckMode = getReadyCheckMode();
11086
11409
  const requestBodyLimit = process.env.MCP_MAX_REQUEST_SIZE?.trim() || "1mb";
11087
11410
  const allowedOrigins = getAllowedOrigins();