@acruxcoreai/mcp-server 0.1.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/bin.mjs CHANGED
@@ -275,10 +275,15 @@ function toApiError(label, status, body) {
275
275
  }
276
276
 
277
277
  // src/format.ts
278
+ var TRUNCATION_MARKER = "\n\n[truncated: response exceeded the size limit \u2014 narrow the query, use a smaller `limit`, or fetch one item at a time]";
279
+ function isTruncated(result) {
280
+ const first = result.content[0];
281
+ return first?.type === "text" && first.text.endsWith(TRUNCATION_MARKER);
282
+ }
278
283
  function truncateText(text, maxBytes) {
279
284
  const encoder = new TextEncoder();
280
285
  if (encoder.encode(text).length <= maxBytes) return text;
281
- const marker = "\n\n[truncated: response exceeded the size limit \u2014 narrow the query, use a smaller `limit`, or fetch one item at a time]";
286
+ const marker = TRUNCATION_MARKER;
282
287
  const budget = Math.max(0, maxBytes - encoder.encode(marker).length);
283
288
  let end = Math.min(text.length, budget);
284
289
  while (end > 0 && encoder.encode(text.slice(0, end)).length > budget) {
@@ -664,10 +669,87 @@ var catalogTools = [
664
669
 
665
670
  // src/toolsets/evaluations.ts
666
671
  import { z as z2 } from "zod";
672
+
673
+ // src/optimize-report.ts
674
+ function summarizeCandidates(grid, cells) {
675
+ const cellByKey = new Map(cells.map((cell) => [cell.cellKey, cell]));
676
+ const baselineByModel = new Map(
677
+ cells.filter((cell) => cell.isProductionBaseline).map((cell) => [cell.model, cell])
678
+ );
679
+ const byCandidate = /* @__PURE__ */ new Map();
680
+ for (const gridCell of grid) {
681
+ if (gridCell.variantKind !== "candidate" || !gridCell.promptCandidateId) continue;
682
+ const reportCell = cellByKey.get(gridCell.cellKey);
683
+ const baseline = baselineByModel.get(gridCell.model);
684
+ let summary = byCandidate.get(gridCell.promptCandidateId);
685
+ if (!summary) {
686
+ summary = {
687
+ candidateId: gridCell.promptCandidateId,
688
+ label: gridCell.variantLabel,
689
+ scores: [],
690
+ beatsBaseline: false
691
+ };
692
+ byCandidate.set(gridCell.promptCandidateId, summary);
693
+ }
694
+ summary.scores.push({
695
+ model: gridCell.model,
696
+ avgScore: reportCell?.avgScore ?? null,
697
+ passRate: reportCell?.passRate ?? null,
698
+ baselineAvgScore: baseline?.avgScore ?? null,
699
+ scoreDelta: reportCell?.deltaVsBaseline?.score ?? null,
700
+ verdict: reportCell?.deltaVsBaseline?.label ?? "unknown"
701
+ });
702
+ }
703
+ const summaries = [...byCandidate.values()];
704
+ for (const summary of summaries) {
705
+ summary.beatsBaseline = summary.scores.some((score) => score.verdict === "improved") && summary.scores.every((score) => score.verdict === "improved" || score.verdict === "flat");
706
+ }
707
+ return summaries.sort((a, b) => a.label.localeCompare(b.label));
708
+ }
709
+ function bestCandidate(candidates) {
710
+ let best = null;
711
+ let bestDelta = -Infinity;
712
+ for (const candidate of candidates) {
713
+ if (!candidate.beatsBaseline) continue;
714
+ const deltas = candidate.scores.map((score) => score.scoreDelta).filter((delta) => delta !== null);
715
+ const mean = deltas.reduce((sum, delta) => sum + delta, 0) / Math.max(1, deltas.length);
716
+ if (mean > bestDelta) {
717
+ best = candidate;
718
+ bestDelta = mean;
719
+ }
720
+ }
721
+ return best;
722
+ }
723
+
724
+ // src/toolsets/evaluations.ts
667
725
  var historyMessageSchema = z2.object({
668
726
  role: z2.enum(["system", "user", "assistant", "tool"]),
669
727
  content: z2.string()
670
728
  });
729
+ async function loadOptimizeRun(client, runId) {
730
+ const run = await client.get(`/runs/${runId}`);
731
+ const notDraftedYet = run.grid.length === 0;
732
+ if (run.kind !== "optimize" && !notDraftedYet) {
733
+ throw new Error(
734
+ `Run ${runId} is an evaluation run, not an optimize run. Read it with get_experiment_run.`
735
+ );
736
+ }
737
+ if (run.status !== "succeeded") return { run, report: null, candidates: [] };
738
+ const report = await client.get(`/runs/${runId}/report`);
739
+ return { run, report, candidates: summarizeCandidates(run.grid, report.cells) };
740
+ }
741
+ function baselineOf(run) {
742
+ const cell = run.grid.find((row) => row.isProductionBaseline && row.promptVersionId);
743
+ if (!cell?.promptVersionId) {
744
+ throw new Error(`Run ${run.id} has no baseline version, so a promote cannot be checked.`);
745
+ }
746
+ const alias = /^v\d+$/.test(cell.variantLabel) ? null : cell.variantLabel;
747
+ return { versionId: cell.promptVersionId, alias };
748
+ }
749
+ function formatDelta(delta) {
750
+ if (delta === null) return "n/a";
751
+ return `${delta >= 0 ? "+" : ""}${delta.toFixed(1)}`;
752
+ }
671
753
  var evaluationTools = [
672
754
  defineTool({
673
755
  name: "list_datasets",
@@ -746,21 +828,29 @@ var evaluationTools = [
746
828
  title: "Create and start an experiment run",
747
829
  toolset: "evaluations",
748
830
  readOnlyHint: false,
749
- description: "Create an experiment over a dataset and immediately start a run of it. The grid is every (version x model) pair you list. When `prompt` is given, a baseline cell for its production alias is added automatically unless that version is already in the grid. Returns as soon as the run is queued \u2014 the worker executes it asynchronously, so poll get_experiment_run for results. Note the judge model (gpt-4o-mini by default) must itself be registered in the gateway or every score fails.",
831
+ description: "Create an experiment over a dataset and immediately start a run of it. The grid is every (version x model) pair you list. When `prompt` is given, a baseline cell for its production alias is added automatically unless that version is already in the grid. Returns as soon as the run is queued \u2014 the worker executes it asynchronously, so poll get_experiment_run for results. `judge_model` scores every answer and must be registered in the gateway (see list_models). `judge_prompt` grades with one of your prompts instead of the built-in judge.",
750
832
  inputSchema: {
751
833
  dataset_id: z2.string().uuid().describe("Dataset to evaluate against."),
752
834
  version_ids: z2.array(z2.string().uuid()).min(1).describe("Prompt-version UUIDs to sweep. At least one."),
753
835
  models: z2.array(z2.string().min(1)).min(1).describe("Gateway model public names to sweep."),
754
836
  prompt: z2.string().optional().describe("Prompt name or UUID under test \u2014 enables the automatic baseline cell."),
755
837
  name: z2.string().optional().describe("Experiment name, for the run history."),
756
- alias: z2.string().optional().describe('Which alias the automatic baseline points at. Default "production".')
838
+ alias: z2.string().optional().describe('Which alias the automatic baseline points at. Default "production".'),
839
+ judge_model: z2.string().min(1).describe("Gateway model that scores every answer. Required."),
840
+ judge_prompt: z2.string().min(1).optional().describe(
841
+ "Name or UUID of a team prompt that grades instead of the built-in judge. The run uses its production version (else its latest). Default: the built-in judge."
842
+ )
757
843
  },
758
844
  async handler(args, { client, config }) {
759
845
  const body = {
760
846
  dataset_id: args.dataset_id,
761
847
  version_ids: args.version_ids,
762
- models: args.models
848
+ models: args.models,
849
+ judge_model: args.judge_model
763
850
  };
851
+ if (args.judge_prompt !== void 0) {
852
+ body.judge_prompt_id = await resolvePromptRef(client, args.judge_prompt);
853
+ }
764
854
  if (args.name !== void 0) body.name = args.name;
765
855
  if (args.alias !== void 0) body.alias = args.alias;
766
856
  if (args.prompt !== void 0) body.prompt_id = await resolvePromptRef(client, args.prompt);
@@ -802,23 +892,214 @@ var evaluationTools = [
802
892
  title: "Get a run, optionally with its comparison report",
803
893
  toolset: "evaluations",
804
894
  readOnlyHint: true,
805
- description: "Read one run's status and results. With include_report=true it also fetches the comparison report: the full (variant x model) matrix with per-cell averages, each cell's delta against the same-model production baseline, a leaderboard and an advisory winner. Ask for the report only once the run has succeeded \u2014 an in-flight run has nothing to compare.",
895
+ description: "Read one run's status and results. With include_report=true it also fetches the comparison report: the full (variant x model) matrix with per-cell averages, each cell's delta against the same-model production baseline, a leaderboard and an advisory winner. Ask for the report only once the run has succeeded \u2014 an in-flight run has nothing to compare. For an optimize run, get_optimize_report gives the same scores per candidate, with the ids promote_optimize_candidate needs.",
806
896
  inputSchema: {
807
897
  run_id: z2.string().uuid().describe("Run UUID."),
808
898
  include_report: z2.boolean().optional().describe("Also fetch the comparison report.")
809
899
  },
810
900
  async handler({ run_id, include_report }, { client, config }) {
811
- const run = await client.get(`/runs/${run_id}`);
901
+ const run = await client.get(
902
+ `/runs/${run_id}`
903
+ );
812
904
  let report = void 0;
813
905
  if (include_report) {
814
906
  report = await client.get(`/runs/${run_id}/report`);
815
907
  }
816
908
  return okResult(
817
- `Run ${run_id} is ${run.status} with ${run.results?.length ?? 0} result(s).`,
909
+ `Run ${run_id} is ${run.status} with ${run.results?.total ?? 0} result(s).`,
818
910
  { run, report },
819
911
  config.maxTextBytes
820
912
  );
821
913
  }
914
+ }),
915
+ defineTool({
916
+ name: "optimize_prompt",
917
+ title: "Start an optimizer run for a prompt",
918
+ toolset: "evaluations",
919
+ readOnlyHint: false,
920
+ description: 'Ask the optimizer to improve a prompt against a dataset. An optimizer model drafts `draft_count` rewrites of the version behind `alias` (default "production"), then every rewrite and that baseline run over the dataset on each of `models`, and `judge_model` scores every answer. Returns the run id as soon as the run is queued \u2014 drafting and scoring take minutes, so poll get_optimize_report. Nothing is promoted automatically: a rewrite only ships when promote_optimize_candidate is called. The dataset\'s examples need `criteria`, or the built-in judge has nothing to grade against. `judge_prompt` grades with one of your prompts instead, and the optimizer reads it too, so the rewrites aim at that rubric. Every model named here must be registered in the gateway (see list_models).',
921
+ inputSchema: {
922
+ prompt: z2.string().min(1).describe("Prompt name or UUID to improve."),
923
+ dataset_id: z2.string().uuid().describe("Dataset whose examples the rewrites are scored on."),
924
+ models: z2.array(z2.string().min(1)).min(1).describe("Gateway model public names to test each rewrite and the baseline on."),
925
+ judge_model: z2.string().min(1).describe("Gateway model that scores every answer. Required."),
926
+ optimizer_model: z2.string().min(1).optional().describe("Gateway model that writes the rewrites. Default: the first entry of `models`."),
927
+ draft_count: z2.number().int().min(1).max(6).optional().describe("How many rewrites to draft, 1 to 6. Default 3."),
928
+ alias: z2.string().min(1).optional().describe('Alias whose version is the baseline to beat. Default "production".'),
929
+ optimizer_prompt: z2.string().optional().describe("Name or UUID of a team prompt to use as the optimizer's instructions."),
930
+ judge_prompt: z2.string().min(1).optional().describe(
931
+ "Name or UUID of a team prompt that grades instead of the built-in judge. The run uses its production version (else its latest). Default: the built-in judge."
932
+ )
933
+ },
934
+ async handler(args, { client, config }) {
935
+ const promptId = await resolvePromptRef(client, args.prompt);
936
+ const body = {
937
+ dataset_id: args.dataset_id,
938
+ models: args.models,
939
+ judge_model: args.judge_model
940
+ };
941
+ if (args.optimizer_model !== void 0) body.optimizer_model = args.optimizer_model;
942
+ if (args.draft_count !== void 0) body.draft_count = args.draft_count;
943
+ if (args.alias !== void 0) body.alias = args.alias;
944
+ if (args.optimizer_prompt !== void 0) {
945
+ body.optimizer_prompt_id = await resolvePromptRef(client, args.optimizer_prompt);
946
+ }
947
+ if (args.judge_prompt !== void 0) {
948
+ body.judge_prompt_id = await resolvePromptRef(client, args.judge_prompt);
949
+ }
950
+ const result = await client.post(`/prompts/${promptId}/optimize`, body);
951
+ const warning = result.prompt_mismatch_warning ? " Warning: some dataset examples were built from a different prompt \u2014 see prompt_mismatch_warning." : "";
952
+ return okResult(
953
+ `Optimize run ${result.run_id} is ${result.status}; ${result.optimizer_model} drafts the rewrites, then they are scored against the ${args.alias ?? "production"} baseline. Poll get_optimize_report with this run id.${warning}`,
954
+ result,
955
+ config.maxTextBytes
956
+ );
957
+ }
958
+ }),
959
+ defineTool({
960
+ name: "get_optimize_report",
961
+ title: "Read an optimizer run's candidates and scores",
962
+ toolset: "evaluations",
963
+ readOnlyHint: true,
964
+ description: "Read an optimize run started by optimize_prompt. While it is queued or running this returns only its status \u2014 call again later. Once it has succeeded it lists every drafted rewrite with its candidate id, the optimizer's rationale, the rewritten messages, and its average score next to the baseline's on each model. `beatsBaseline` is true only for a rewrite that improved on at least one model and was improved or flat on every other; `recommended` is the one among those with the largest gain, or null when no rewrite beat the baseline. When the rewrites are too long to fit in one result, their messages are left out (`messagesOmitted`); pass `candidate_id` to read one rewrite in full.",
965
+ inputSchema: {
966
+ run_id: z2.string().uuid().describe("Optimize run UUID, from optimize_prompt."),
967
+ candidate_id: z2.string().uuid().optional().describe("Return only this candidate, with its full messages.")
968
+ },
969
+ async handler({ run_id, candidate_id }, { client, config }) {
970
+ const { run, report, candidates } = await loadOptimizeRun(client, run_id);
971
+ if (run.status === "queued" || run.status === "running") {
972
+ return okResult(
973
+ `Optimize run ${run_id} is ${run.status}. No scores yet \u2014 call get_optimize_report again shortly.`,
974
+ { runId: run_id, status: run.status },
975
+ config.maxTextBytes
976
+ );
977
+ }
978
+ if (run.status === "failed") {
979
+ return okResult(
980
+ `Optimize run ${run_id} failed: ${run.error ?? "no reason recorded"}. Nothing to promote.`,
981
+ { runId: run_id, status: run.status, error: run.error },
982
+ config.maxTextBytes
983
+ );
984
+ }
985
+ if (candidate_id !== void 0) {
986
+ const candidate = candidates.find((row) => row.candidateId === candidate_id);
987
+ if (!candidate) {
988
+ throw new Error(`Candidate ${candidate_id} is not a rewrite from run ${run_id}.`);
989
+ }
990
+ const detail = await client.get(
991
+ `/runs/${run_id}/candidates/${candidate_id}`
992
+ );
993
+ return okResult(
994
+ `${candidate.label} (candidate_id ${candidate_id}) from optimize run ${run_id}; beatsBaseline: ${candidate.beatsBaseline}.`,
995
+ {
996
+ runId: run_id,
997
+ candidate: { ...candidate, rationale: detail.rationale, messages: detail.messages }
998
+ },
999
+ config.maxTextBytes
1000
+ );
1001
+ }
1002
+ const reads = await Promise.allSettled(
1003
+ candidates.map(
1004
+ (candidate) => client.get(`/runs/${run_id}/candidates/${candidate.candidateId}`)
1005
+ )
1006
+ );
1007
+ const withContent = candidates.map((candidate, index) => {
1008
+ const read = reads[index];
1009
+ return read.status === "fulfilled" ? { ...candidate, rationale: read.value.rationale, messages: read.value.messages } : {
1010
+ ...candidate,
1011
+ rationale: null,
1012
+ messages: null,
1013
+ readError: read.reason instanceof Error ? read.reason.message : String(read.reason)
1014
+ };
1015
+ });
1016
+ const best = bestCandidate(candidates);
1017
+ const winners = candidates.filter((candidate) => candidate.beatsBaseline).length;
1018
+ const rejected = report?.optimizerRejections ?? [];
1019
+ const rejectedNote = rejected.length > 0 ? ` ${rejected.length} more rewrite(s) were dropped before scoring: ${rejected.join(" | ")}.` : "";
1020
+ const summary = (best ? `Optimize run ${run_id} succeeded. ${winners} of ${candidates.length} rewrite(s) beat the baseline. Recommended: ${best.label} (candidate_id ${best.candidateId}), ` + best.scores.map((score) => `${formatDelta(score.scoreDelta)} on ${score.model}`).join(", ") + ". Promote it with promote_optimize_candidate only if the user agrees." : `Optimize run ${run_id} succeeded, but none of its ${candidates.length} rewrite(s) beat the baseline. Nothing is worth promoting; keep the current version.`) + rejectedNote;
1021
+ const payload = {
1022
+ runId: run_id,
1023
+ status: run.status,
1024
+ judgeModel: report?.judge?.model ?? null,
1025
+ // Null means the built-in judge graded the run.
1026
+ judgePromptVersionId: report?.judge?.promptVersionId ?? null,
1027
+ recommended: best?.candidateId ?? null,
1028
+ rejectedRewrites: rejected,
1029
+ baseline: (report?.cells ?? []).filter((cell) => cell.isProductionBaseline).map((cell) => ({
1030
+ label: cell.variantLabel,
1031
+ model: cell.model,
1032
+ avgScore: cell.avgScore,
1033
+ passRate: cell.passRate
1034
+ })),
1035
+ candidates: withContent
1036
+ };
1037
+ const full = okResult(summary, payload, config.maxTextBytes);
1038
+ if (!isTruncated(full)) return full;
1039
+ return okResult(
1040
+ `${summary} The rewrites are too long to show together, so their messages are left out; call get_optimize_report again with candidate_id to read one.`,
1041
+ {
1042
+ ...payload,
1043
+ messagesOmitted: true,
1044
+ candidates: withContent.map(({ messages: _messages, ...rest }) => rest)
1045
+ },
1046
+ config.maxTextBytes
1047
+ );
1048
+ }
1049
+ }),
1050
+ defineTool({
1051
+ name: "promote_optimize_candidate",
1052
+ title: "Ship an optimizer rewrite as a new prompt version",
1053
+ toolset: "evaluations",
1054
+ readOnlyHint: false,
1055
+ destructiveHint: true,
1056
+ description: "Commit one rewrite from a succeeded optimize run as a new prompt version and move `alias` to it, so live traffic on that alias starts using it. `alias` defaults to the alias the run was scored against (production when the run used the latest version). Take `candidate_id` from get_optimize_report. Refuses a rewrite that did not beat the baseline, and refuses when the alias now points at a version other than the one the run scored against; set `promote_without_improvement` only when the user has explicitly asked to ship that rewrite anyway. Undo by moving the alias back with promote_prompt_alias.",
1057
+ inputSchema: {
1058
+ run_id: z2.string().uuid().describe("Optimize run UUID."),
1059
+ candidate_id: z2.string().uuid().describe("Candidate id from get_optimize_report."),
1060
+ alias: z2.string().min(1).optional().describe("Alias to move. Default: the alias the run was scored against."),
1061
+ promote_without_improvement: z2.boolean().optional().describe(
1062
+ "Ship a rewrite that did not beat the baseline, or replace a version the run never scored. Only on the user's explicit say-so."
1063
+ )
1064
+ },
1065
+ async handler(args, { client, config }) {
1066
+ const { run, candidates } = await loadOptimizeRun(client, args.run_id);
1067
+ if (run.status !== "succeeded") {
1068
+ throw new Error(
1069
+ `Optimize run ${args.run_id} is ${run.status}, so its rewrites are not fully scored. Promote only from a succeeded run.`
1070
+ );
1071
+ }
1072
+ const candidate = candidates.find((row) => row.candidateId === args.candidate_id);
1073
+ if (!candidate) {
1074
+ throw new Error(
1075
+ `Candidate ${args.candidate_id} is not a rewrite from run ${args.run_id}. Take the id from get_optimize_report.`
1076
+ );
1077
+ }
1078
+ if (!candidate.beatsBaseline && !args.promote_without_improvement) {
1079
+ const scores = candidate.scores.map((score) => `${formatDelta(score.scoreDelta)} (${score.verdict}) on ${score.model}`).join(", ");
1080
+ throw new Error(
1081
+ `Refused: ${candidate.label} did not beat the baseline (${scores}). Promoting it would ship a prompt that scored no better than the current one. Set promote_without_improvement to true only if the user explicitly asked for this rewrite.`
1082
+ );
1083
+ }
1084
+ const baseline = baselineOf(run);
1085
+ const alias = args.alias ?? baseline.alias ?? "production";
1086
+ const detail = await client.get(
1087
+ `/runs/${args.run_id}/candidates/${args.candidate_id}`
1088
+ );
1089
+ const aliases = await client.get(`/prompts/${detail.promptId}/aliases`);
1090
+ const live = aliases.find((row) => row.alias === alias);
1091
+ if (live && live.versionId !== baseline.versionId && !args.promote_without_improvement) {
1092
+ throw new Error(
1093
+ `Refused: alias "${alias}" now points at version ${live.versionNumber}, but run ${args.run_id} scored its rewrites against a different version. Nothing compared ${candidate.label} with version ${live.versionNumber}. Start a new optimize run against this alias, or set promote_without_improvement to true only if the user explicitly asked to replace it anyway.`
1094
+ );
1095
+ }
1096
+ const result = await client.post(`/runs/${args.run_id}/promote`, { prompt_candidate_id: args.candidate_id, alias });
1097
+ return okResult(
1098
+ `Promoted ${candidate.label} as version ${result.version.versionNumber}; alias "${result.alias.alias}" now points at it.`,
1099
+ result,
1100
+ config.maxTextBytes
1101
+ );
1102
+ }
822
1103
  })
823
1104
  ];
824
1105
 
@@ -845,6 +1126,9 @@ function gatewayMeta(headers) {
845
1126
  }
846
1127
  return meta;
847
1128
  }
1129
+ function traceSuffix(meta) {
1130
+ return meta["trace-id"] ? ` Open it with get_trace, trace_id ${meta["trace-id"]}.` : "";
1131
+ }
848
1132
  function firstChoiceText(body) {
849
1133
  const choice = body?.choices?.[0];
850
1134
  const content = choice?.message?.content;
@@ -889,9 +1173,7 @@ var gatewayTools = [
889
1173
  });
890
1174
  const meta = gatewayMeta(response.headers);
891
1175
  return okResult(
892
- `Ran "${name}"@${args.alias ?? "production"} on ${meta.model ?? "the resolved model"}${meta["cost-usd"] ? ` for $${meta["cost-usd"]}` : ""}. Reply: ${firstChoiceText(
893
- response.data
894
- ).slice(0, 400)}`,
1176
+ `Ran "${name}"@${args.alias ?? "production"} on ${meta.model ?? "the resolved model"}${meta["cost-usd"] ? ` for $${meta["cost-usd"]}` : ""}.${traceSuffix(meta)} Reply: ` + firstChoiceText(response.data).slice(0, 400),
895
1177
  { completion: response.data, gateway: meta },
896
1178
  config.maxTextBytes
897
1179
  );
@@ -932,9 +1214,7 @@ var gatewayTools = [
932
1214
  });
933
1215
  const meta = gatewayMeta(response.headers);
934
1216
  return okResult(
935
- `Completion from ${meta.model ?? args.model}${meta["cost-usd"] ? ` ($${meta["cost-usd"]})` : ""}: ${firstChoiceText(
936
- response.data
937
- ).slice(0, 400)}`,
1217
+ `Completion from ${meta.model ?? args.model}${meta["cost-usd"] ? ` ($${meta["cost-usd"]})` : ""}.${traceSuffix(meta)} Reply: ` + firstChoiceText(response.data).slice(0, 400),
938
1218
  { completion: response.data, gateway: meta },
939
1219
  config.maxTextBytes
940
1220
  );
@@ -974,6 +1254,37 @@ var gatewayTools = [
974
1254
  config.maxTextBytes
975
1255
  );
976
1256
  }
1257
+ }),
1258
+ defineTool({
1259
+ name: "get_spending_limits",
1260
+ title: "Get budgets and virtual-key limits",
1261
+ toolset: "gateway",
1262
+ readOnlyHint: true,
1263
+ description: "Every spend budget on the team \u2014 team-wide or on one virtual key \u2014 with its period, limit, live spend, what is left and when it resets, plus each virtual key's rate limits and model/provider allow-lists. Use this after a gateway call is refused with HTTP 402 (budget spent) or 429 (rate limit) to see which limit caused it. Read-only: budgets and keys are changed in the dashboard.",
1264
+ inputSchema: {},
1265
+ async handler(_args, { client, config }) {
1266
+ const [budgets, keys] = await Promise.all([
1267
+ client.get("/gateway/budgets"),
1268
+ client.get("/gateway/keys")
1269
+ ]);
1270
+ const keyNames = new Map(keys.map((k) => [k.id, k.name]));
1271
+ const limits = budgets.map((b) => ({
1272
+ id: b.id,
1273
+ scope: b.virtualKeyId === null ? "team" : "virtual_key",
1274
+ virtualKeyId: b.virtualKeyId,
1275
+ virtualKeyName: b.virtualKeyId === null ? null : keyNames.get(b.virtualKeyId) ?? null,
1276
+ period: b.period,
1277
+ limitUsd: b.limitUsd,
1278
+ spendUsd: b.spendUsd,
1279
+ remainingUsd: Math.max(0, b.limitUsd - b.spendUsd),
1280
+ exhausted: b.spendUsd >= b.limitUsd,
1281
+ resetsAt: b.resetsAt
1282
+ }));
1283
+ const summary = limits.length === 0 ? `No budgets on this team, so the gateway never refuses a call for spend. ${keys.length} virtual key(s).` : `${limits.length} budget(s), ${keys.length} virtual key(s). ` + limits.map(
1284
+ (l) => `${l.scope === "team" ? "Team" : `Key "${l.virtualKeyName ?? l.virtualKeyId}"`} ${l.period}: $${l.spendUsd} of $${l.limitUsd} spent` + (l.exhausted ? " (EXHAUSTED)" : "") + (l.resetsAt ? `, resets ${l.resetsAt}` : "")
1285
+ ).join("; ") + ".";
1286
+ return okResult(summary, { budgets: limits, virtualKeys: keys }, config.maxTextBytes);
1287
+ }
977
1288
  })
978
1289
  ];
979
1290
 
@@ -1339,7 +1650,7 @@ function selectTools(config) {
1339
1650
  }
1340
1651
 
1341
1652
  // src/server.ts
1342
- var SERVER_VERSION = "0.1.0";
1653
+ var SERVER_VERSION = "0.3.0";
1343
1654
  function buildInstructions(toolNames, readOnly) {
1344
1655
  const parts = [
1345
1656
  `AcruxCore is an LLM-ops platform: a prompt registry, a versioned tool catalog, an AI gateway, tracing, and evaluation.