@mcpjam/cli 5.11.4 → 5.12.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/index.js CHANGED
@@ -1,17 +1,17 @@
1
1
  #!/usr/bin/env node
2
2
  import { Command, CommanderError, Option } from 'commander';
3
- import { realpathSync, readFileSync, existsSync, mkdirSync, writeFileSync, unlinkSync, statSync, closeSync, renameSync, openSync } from 'fs';
3
+ import { realpathSync, readFileSync, existsSync, mkdirSync, writeFileSync, unlinkSync, statSync, closeSync, renameSync, lstatSync, openSync } from 'fs';
4
4
  import { pathToFileURL } from 'url';
5
- import { probeMcpServer, redactForTelemetry, runServerDoctor, collectServerSnapshot, serializeStableServerSnapshot, serializeServerSnapshot, buildServerDiffReport, classifyMcpHeader, validateToolCallResult, isCallToolResultError, buildToolCallValidationReport, listResources, readResource, listServerSkillCatalog, getVerifiedServerSkill, isServerSkillRefusalError, readVerifiedServerSkillFile, SubscriptionCoordinator, listTools, listPrompts, getPrompt, MCPAppsConformanceTest, scoreFromAppsResult, MCPAppsConformanceSuite, MCPTasksConformanceTest, scoreFromTasksResult, runOAuthLogin, OAuthConformanceTest, scoreFromOAuthResult, OAuthConformanceSuite, runXaaFlow, MCPConformanceTest, scoreFromProtocolResult, MCPConformanceSuite, runConformance, isConformanceReportingConfigured, reportConformanceRun, reportConformanceRunSafely, OPENAI_SUBMISSION_MODES, withEphemeralClient, diffServerSnapshots, ServerSnapshotFormatError, renderStructuredRunJUnitXml, renderStructuredRunHtml, renderStructuredRunJson, DEFAULT_SUBSCRIPTION_RECONNECT_POLICY, isKnownProtocolVersion, describeConformanceScore, toConformanceReport, buildConformanceRunReport, renderConformanceReportJUnitXml, renderConformanceReportJson, formatOAuthConformanceHuman, formatOAuthConformanceSuiteHuman, fetchOAuthMetadata, executeOAuthProxy, executeDebugOAuthProxy, normalizeRegistrationStrategy, normalizeXaaClientAuth, normalizeIdentityAssertionFormat, IDENTITY_ASSERTION_FORMATS, XAA_CONFIDENTIAL_CIMD_ORIGIN, getLocalConfidentialCimdProvider, MCP_PROTOCOL_VERSIONS, gatherClaudeReadinessEvidence, gradeClaudeReadiness, gatherOpenAIReadinessEvidence, xmldomParseXml, gradeOpenAIReadiness, openUrlInBrowser, buildEvalRunReport, GATE_WAIVER_MAX_REASON_LENGTH, GATE_WAIVER_REASON_NOTICE, MCPClientManager, withSkillsExtensionCapability, MCP_SKILLS_EXTENSION_ID, decodeMcpHeaderValue, canDeclareTasksExtension, createStrictElicitationContentValidator, MCP_APPS_CHECK_CATEGORIES, MCP_APPS_CHECK_IDS, MCP_TASKS_CHECK_CATEGORIES, MCP_TASKS_CHECK_IDS, OAuthProxyError, isLoopbackHost, MCP_CHECK_CATEGORIES, MCP_CHECK_IDS, OPENAI_SUBMISSION_MODE_SHAPES, createDirectoryPluginFileSource, collectZipArchiveObservations, createZipPluginFileSource, generateRandomString, generateCodeChallenge, createInteractiveAuthorizationSession, loadEvalSuiteFile, declareEvalSuiteFileValidity, formatEvalRunDecisionSummary, gateOutcomeVerdict, applyGateWaiver, formatGateReport, formatGateWaiverLine, detectFlakyCases, evaluateCompareGates, buildRunCompareReport, formatSuiteFileFindings, serializeEvalSuiteFile, MAX_SUITE_FILE_BYTES, buildCorpus, HostedOnlyCaseError, verifyCorpusLock, detectCiMetadata, TaskLifecycleEngine, driveTaskToTerminal, extensionTaskToObservation, legacyTaskToObservation, executionRailLabel, executionDeviationTitle, canonicalDigest, readEvalRunDecisionSummary as readEvalRunDecisionSummary$1, buildEvalRunDecisionSummary, readExecutionRecord, formatExecutionProvenanceLine, formatExecutionDeviationLine, evaluateGates, gateInputFromPlatformRun, isGateWaiverInForce, calculateLatencyStats, CORPUS_LOCK_VERSION, suiteFilePointer, passRateFractionFromPercent, DEFAULT_MIN_EFFECT_SIZE, DEFAULT_MIN_SAMPLE_SIZE, planPlatformSuiteGradingUpdate, isUnknownTaskError, isMCPTasksWireError, LEGACY_TASK_STATUSES } from '@mcpjam/sdk';
5
+ import { loadEvalSuiteFile, createSuiteFileRunner, runSuiteFile, SuiteFileRunError, formatLocalEvalRunSummary, renderStructuredRunJson, probeMcpServer, redactForTelemetry, runServerDoctor, collectServerSnapshot, serializeStableServerSnapshot, serializeServerSnapshot, buildServerDiffReport, classifyMcpHeader, validateToolCallResult, isCallToolResultError, buildToolCallValidationReport, listResources, readResource, listServerSkillCatalog, getVerifiedServerSkill, isServerSkillRefusalError, readVerifiedServerSkillFile, SubscriptionCoordinator, listTools, listPrompts, getPrompt, MCPAppsConformanceTest, scoreFromAppsResult, MCPAppsConformanceSuite, MCPTasksConformanceTest, scoreFromTasksResult, runOAuthLogin, OAuthConformanceTest, scoreFromOAuthResult, OAuthConformanceSuite, runXaaFlow, MCPConformanceTest, scoreFromProtocolResult, MCPConformanceSuite, runConformance, isConformanceReportingConfigured, reportConformanceRun, reportConformanceRunSafely, OPENAI_SUBMISSION_MODES, renderStructuredRunJUnitXml, renderStructuredRunHtml, withEphemeralClient, diffServerSnapshots, ServerSnapshotFormatError, DEFAULT_SUBSCRIPTION_RECONNECT_POLICY, isKnownProtocolVersion, describeConformanceScore, toConformanceReport, buildConformanceRunReport, renderConformanceReportJUnitXml, renderConformanceReportJson, formatOAuthConformanceHuman, formatOAuthConformanceSuiteHuman, fetchOAuthMetadata, executeOAuthProxy, executeDebugOAuthProxy, normalizeRegistrationStrategy, normalizeXaaClientAuth, normalizeIdentityAssertionFormat, IDENTITY_ASSERTION_FORMATS, XAA_CONFIDENTIAL_CIMD_ORIGIN, getLocalConfidentialCimdProvider, MCP_PROTOCOL_VERSIONS, gatherClaudeReadinessEvidence, gradeClaudeReadiness, gatherOpenAIReadinessEvidence, xmldomParseXml, gradeOpenAIReadiness, openUrlInBrowser, buildEvalRunReport, GATE_WAIVER_MAX_REASON_LENGTH, GATE_WAIVER_REASON_NOTICE, MCPClientManager, withSkillsExtensionCapability, detectCiMetadata, MCP_SKILLS_EXTENSION_ID, decodeMcpHeaderValue, canDeclareTasksExtension, createStrictElicitationContentValidator, MCP_APPS_CHECK_CATEGORIES, MCP_APPS_CHECK_IDS, MCP_TASKS_CHECK_CATEGORIES, MCP_TASKS_CHECK_IDS, OAuthProxyError, isLoopbackHost, MCP_CHECK_CATEGORIES, MCP_CHECK_IDS, OPENAI_SUBMISSION_MODE_SHAPES, createDirectoryPluginFileSource, collectZipArchiveObservations, createZipPluginFileSource, generateRandomString, generateCodeChallenge, createInteractiveAuthorizationSession, declareEvalSuiteFileValidity, formatEvalRunDecisionSummary, gateOutcomeVerdict, applyGateWaiver, formatGateReport, formatGateWaiverLine, detectFlakyCases, evaluateCompareGates, buildRunCompareReport, formatSuiteFileFindings, serializeEvalSuiteFile, MAX_SUITE_FILE_BYTES, buildCorpus, HostedOnlyCaseError, verifyCorpusLock, TaskLifecycleEngine, driveTaskToTerminal, extensionTaskToObservation, legacyTaskToObservation, canonicalDigest, readEvalRunDecisionSummary as readEvalRunDecisionSummary$1, buildEvalRunDecisionSummary, evaluateGates, gateInputFromPlatformRun, isGateWaiverInForce, calculateLatencyStats, CORPUS_LOCK_VERSION, suiteFilePointer, passRateFractionFromPercent, DEFAULT_MIN_EFFECT_SIZE, DEFAULT_MIN_SAMPLE_SIZE, planPlatformSuiteGradingUpdate, isUnknownTaskError, isMCPTasksWireError, LEGACY_TASK_STATUSES } from '@mcpjam/sdk';
6
6
  import path7, { join, dirname, basename, resolve } from 'path';
7
7
  import { randomUUID, randomBytes, createHash } from 'crypto';
8
8
  import { mkdir, writeFile, readFile, chmod, rename, rm, open, unlink, stat } from 'fs/promises';
9
9
  import { spawn } from 'child_process';
10
10
  import { createRequire } from 'module';
11
11
  import os, { homedir, tmpdir } from 'os';
12
- import { RUN_LAUNCH_HEADERS, getRegistryDirectoryServerOperation, listOrganizationsOperation, listProjectsOperation, createProjectOperation, updateProjectOperation, deleteProjectOperation, connectProjectServerOperation, getProjectServerConnectionStatusOperation, cancelProjectServerConnectionOperation, listChatSessionsOperation, resolveProject, sendChatMessageOperation, createTunnelOperation, listEvalSuiteRunsOperation, listEvalSuiteRevisionsOperation, runEvalSuiteOperation, getEvalRunOperation, getEvalRunRouteFactsOperation, getEvalRunServerFactsOperation, proposeEvalDescriptionRewriteOperation, startEvalDescriptionExperimentOperation, getEvalDescriptionExperimentOperation, cancelEvalRunOperation, backtestEvalRunJudgeOperation, backtestEvalRunOperation, requestEvalRunJudgeOperation, listEvalRunIterationsOperation, getEvalIterationTraceOperation, getEvalRunStepsOperation, getEvalSuiteOperation, updateEvalSuiteOperation, deleteEvalSuiteOperation, setEvalSuiteScheduleOperation, setEvalSuiteEnvironmentsOperation, listEvalCasesOperation, getEvalCaseOperation, createEvalCaseOperation, updateEvalCaseOperation, deleteEvalCaseOperation, generateEvalCasesOperation, importEvalCasesOperation, createClientOperation, updateClientOperation, setClientServersOperation, duplicateClientOperation, createEnvironmentOperation, ensureAdhocEnvironmentOperation, nameEnvironmentOperation, updateEnvironmentOperation, createSecretOperation, updateSecretOperation, createImageOperation, validateImageBlueprintOperation, updateImageOperation, listTraceDestinationsOperation, getTraceDestinationOperation, createTraceDestinationOperation, updateTraceDestinationOperation, deleteTraceDestinationOperation, testTraceDestinationOperation, pauseTraceDestinationOperation, resumeTraceDestinationOperation, backfillTraceDestinationOperation, listTraceDestinationBackfillsOperation, runOperationWithPermalinks, withPermalinkEnvelope, PlatformApiError, installRegistryServerOperation, installRegistryDirectoryServerOperation, getProjectServerOperation, DEFAULT_PLATFORM_API_BASE_URL, projectResolutionError, listProjectServersOperation, createProjectServerOperation, updateProjectServerOperation, deleteProjectServerOperation, showServersOperation, driveChatSessionBrowserOperation, observeChatSessionBrowserOperation, isPlatformApiError, describePlatformRefusal, platformRefusalHint, createEvalSuiteOperation, listEvalSuitesOperation, buildAppPermalink, listEvalSuiteStageAnalyticsOperation, getEvalRunStageAnalyticsOperation, listEvalGithubReposOperation, connectEvalGithubRepoOperation, resolveEnvironmentOperation, listClientsOperation, getClientOperation, deleteClientOperation, listEnvironmentsOperation, getEnvironmentOperation, getEnvironmentCapabilitiesOperation, archiveEnvironmentOperation, restoreEnvironmentOperation, listSecretsOperation, getSecretOperation, deleteSecretOperation, listImagesOperation, getImageOperation, buildImageOperation, listImageBuildsOperation, useImageOperation, resetComputerOperation, promoteImageOperation, deleteImageOperation, listProjectSkillsOperation, getProjectSkillOperation, listGoalsOperation, listGoalRunsOperation, getGoalRunOperation, launchGoalRunOperation, cancelGoalRunOperation, listGoalRunSessionsOperation, PlatformApiClient, platformBrowserToolPolicySchema, listServerToolsOperation, runEvalCaseOperation, getCapabilitiesOperation, getStudyOperation, listStudySessionsOperation, getStudySessionOperation, getStudyMetricsOperation, getStudyUsageOperation, listStudyFindingsOperation, getStudySignalsOperation, getStudyInsightsOperation, requestStudyInsightsOperation, cancelStudyInsightsOperation, dismissStudyFindingOperation, undismissStudyFindingOperation, updateStudyOperation, setStudyGuestExecutionOperation, rotateStudyLinkOperation, upsertStudyMemberOperation, removeStudyMemberOperation, rebindStudyOperation, listStudiesOperation, publishStudyOperation, unpublishStudyOperation, searchSessionsOperation, getChatSessionOperation, getChatSessionTraceOperation, listPersonasOperation, getPersonaOperation, createPersonaOperation, updatePersonaOperation, deletePersonaOperation, generatePersonasOperation, getGoalOperation, createGoalOperation, updateGoalOperation, archiveGoalOperation, generateGoalsOperation, getSwarmOverviewOperation, getGoalRunScorecardOperation, listSwarmFindingsOperation, dismissSwarmFindingOperation, undismissSwarmFindingOperation, getSwarmRunInsightsOperation, requestSwarmRunInsightsOperation, cancelSwarmRunInsightsOperation, listSwarmsOperation, getSwarmOperation, createSwarmOperation, updateSwarmOperation, archiveSwarmOperation, startClaudeReadinessRunOperation, startOpenAIReadinessRunOperation, getReadinessRunOperation, listReadinessRunsOperation, cancelReadinessRunOperation, getReadinessReportOperation, listRegistryDirectorySourcesOperation, searchRegistryDirectoryOperation, listRegistryServersOperation, listRegistryConnectionsOperation, uninstallRegistryServerOperation } from '@mcpjam/sdk/platform';
12
+ import { RUN_LAUNCH_HEADERS, getRegistryDirectoryServerOperation, isPlatformApiError, resolveProject, listOrganizationsOperation, listProjectsOperation, createProjectOperation, updateProjectOperation, deleteProjectOperation, connectProjectServerOperation, getProjectServerConnectionStatusOperation, cancelProjectServerConnectionOperation, listChatSessionsOperation, sendChatMessageOperation, createTunnelOperation, listEvalSuiteRunsOperation, listEvalSuiteRevisionsOperation, runEvalSuiteOperation, getEvalRunOperation, getEvalRunRouteFactsOperation, getEvalRunServerFactsOperation, proposeEvalDescriptionRewriteOperation, startEvalDescriptionExperimentOperation, getEvalDescriptionExperimentOperation, cancelEvalRunOperation, backtestEvalRunJudgeOperation, backtestEvalRunOperation, requestEvalRunJudgeOperation, listEvalRunIterationsOperation, getEvalIterationTraceOperation, getEvalRunStepsOperation, getEvalSuiteOperation, updateEvalSuiteOperation, deleteEvalSuiteOperation, setEvalSuiteScheduleOperation, setEvalSuiteEnvironmentsOperation, listEvalCasesOperation, getEvalCaseOperation, createEvalCaseOperation, updateEvalCaseOperation, deleteEvalCaseOperation, generateEvalCasesOperation, importEvalCasesOperation, createClientOperation, updateClientOperation, setClientServersOperation, duplicateClientOperation, createEnvironmentOperation, ensureAdhocEnvironmentOperation, nameEnvironmentOperation, updateEnvironmentOperation, createSecretOperation, updateSecretOperation, createImageOperation, validateImageBlueprintOperation, updateImageOperation, listTraceDestinationsOperation, getTraceDestinationOperation, createTraceDestinationOperation, updateTraceDestinationOperation, deleteTraceDestinationOperation, testTraceDestinationOperation, pauseTraceDestinationOperation, resumeTraceDestinationOperation, backfillTraceDestinationOperation, listTraceDestinationBackfillsOperation, runOperationWithPermalinks, withPermalinkEnvelope, PlatformApiError, installRegistryServerOperation, installRegistryDirectoryServerOperation, getProjectServerOperation, DEFAULT_PLATFORM_API_BASE_URL, PlatformApiClient, projectResolutionError, listProjectServersOperation, createProjectServerOperation, updateProjectServerOperation, deleteProjectServerOperation, showServersOperation, driveChatSessionBrowserOperation, observeChatSessionBrowserOperation, describePlatformRefusal, platformRefusalHint, createEvalSuiteOperation, listEvalSuitesOperation, buildAppPermalink, listEvalSuiteStageAnalyticsOperation, getEvalRunStageAnalyticsOperation, listEvalGithubReposOperation, connectEvalGithubRepoOperation, resolveEnvironmentOperation, listClientsOperation, getClientOperation, deleteClientOperation, listEnvironmentsOperation, getEnvironmentOperation, getEnvironmentCapabilitiesOperation, archiveEnvironmentOperation, restoreEnvironmentOperation, listSecretsOperation, getSecretOperation, deleteSecretOperation, listImagesOperation, getImageOperation, buildImageOperation, listImageBuildsOperation, useImageOperation, resetComputerOperation, promoteImageOperation, deleteImageOperation, listProjectSkillsOperation, getProjectSkillOperation, listGoalsOperation, listGoalRunsOperation, getGoalRunOperation, launchGoalRunOperation, cancelGoalRunOperation, listGoalRunSessionsOperation, platformBrowserToolPolicySchema, listServerToolsOperation, runEvalCaseOperation, sendFeedbackOperation, getCapabilitiesOperation, getStudyOperation, listStudySessionsOperation, getStudySessionOperation, getStudyMetricsOperation, getStudyUsageOperation, listStudyFindingsOperation, getStudySignalsOperation, getStudyInsightsOperation, requestStudyInsightsOperation, cancelStudyInsightsOperation, dismissStudyFindingOperation, undismissStudyFindingOperation, updateStudyOperation, setStudyGuestExecutionOperation, rotateStudyLinkOperation, upsertStudyMemberOperation, removeStudyMemberOperation, rebindStudyOperation, listStudiesOperation, publishStudyOperation, unpublishStudyOperation, searchSessionsOperation, getChatSessionOperation, getChatSessionTraceOperation, listPersonasOperation, getPersonaOperation, createPersonaOperation, updatePersonaOperation, deletePersonaOperation, generatePersonasOperation, getGoalOperation, createGoalOperation, updateGoalOperation, archiveGoalOperation, generateGoalsOperation, getSwarmOverviewOperation, getGoalRunScorecardOperation, listSwarmFindingsOperation, dismissSwarmFindingOperation, undismissSwarmFindingOperation, getSwarmRunInsightsOperation, requestSwarmRunInsightsOperation, cancelSwarmRunInsightsOperation, listSwarmsOperation, getSwarmOperation, createSwarmOperation, updateSwarmOperation, archiveSwarmOperation, startClaudeReadinessRunOperation, startOpenAIReadinessRunOperation, getReadinessRunOperation, listReadinessRunsOperation, cancelReadinessRunOperation, getReadinessReportOperation, listRegistryDirectorySourcesOperation, searchRegistryDirectoryOperation, listRegistryServersOperation, listRegistryConnectionsOperation, uninstallRegistryServerOperation } from '@mcpjam/sdk/platform';
13
13
  import { isDeepStrictEqual } from 'util';
14
- import { swarmVerdictLabel, composeSuiteGateWithBaseReport, EVAL_SUITE_SCHEMA_VERSION, EVAL_SUITE_SCHEMA_VERSIONS, MAX_BATCH_CREATE_CASES, filterSuppressedSuiteAssertions, evalSuiteFileSchema, MAX_IMPORT_NOTE_CHARS, isOpaqueId } from '@mcpjam/sdk/contract';
14
+ import { swarmVerdictLabel, composeSuiteGateWithBaseReport, EVAL_SUITE_SCHEMA_VERSION, EVAL_SUITE_SCHEMA_VERSIONS, MAX_BATCH_CREATE_CASES, filterSuppressedSuiteAssertions, LEGACY_SUITE_WIDE_THRESHOLD_PERCENT, evalSuiteFileSchema, MAX_IMPORT_NOTE_CHARS, isOpaqueId } from '@mcpjam/sdk/contract';
15
15
  import { HOST_TEMPLATES, HOST_TEMPLATE_IDS, seedHostTemplate } from '@mcpjam/sdk/host-config/templates';
16
16
  import { setTimeout as setTimeout$1 } from 'timers/promises';
17
17
  import http from 'http';
@@ -19,16 +19,17 @@ import https from 'https';
19
19
  import { once } from 'events';
20
20
  import { WebSocket } from 'ws';
21
21
  import { buildHostProfilesFromCatalog, buildMarketHostProfiles, scanWidgetUsage, evaluateMarketHosts, fetchHostCompatCatalog } from '@mcpjam/sdk/host-compat';
22
- import { applyVisibilityPolicyAndCountSignals, isAppOnlyTool, extractHostExecutionPolicy, hostConnectionProfile } from '@mcpjam/sdk/host-config/internal';
22
+ import { applyVisibilityPolicyAndCountSignals, isAppOnlyTool, extractHostExecutionPolicy, hostConnectionProfile, applyHostConnectionProfile } from '@mcpjam/sdk/host-config/internal';
23
23
  import * as readline from 'readline/promises';
24
24
  import { StdioServerTransport } from '@modelcontextprotocol/server/stdio';
25
25
  import { McpServer } from '@modelcontextprotocol/server';
26
26
  import { z } from 'zod';
27
27
  import { PostHog } from 'posthog-node';
28
+ import { selectPluginMcpServerMap, detectPluginMcpTransport } from '@mcpjam/sdk/plugin-bundle';
28
29
 
29
30
  // package.json
30
31
  var package_default = {
31
- version: "5.11.4"};
32
+ version: "5.12.0"};
32
33
  function conformanceExitCode(result) {
33
34
  if (result.outcome === "incomplete") return 3;
34
35
  if (result.outcome === "failed") return 1;
@@ -918,7 +919,7 @@ function isAccessTokenUsable(contents, now) {
918
919
  }
919
920
  return Date.parse(contents.expiresAt) - now.getTime() > ACCESS_TOKEN_EXPIRY_SKEW_MS;
920
921
  }
921
- var readTextFile = (path9, encoding) => readFileSync(path9, encoding);
922
+ var readTextFile = (path11, encoding) => readFileSync(path11, encoding);
922
923
  var JsonInputContext = class {
923
924
  constructor(readFile3 = readTextFile) {
924
925
  this.readFile = readFile3;
@@ -1569,7 +1570,9 @@ async function ensureInspector(options = {}) {
1569
1570
  });
1570
1571
  const url2 = buildInspectorUrl(browserBaseUrl3, options.tab);
1571
1572
  if (options.openBrowser && !health.hasActiveClient) {
1572
- openUrl(url2);
1573
+ openUrl(
1574
+ buildInspectorAccessUrl(url2, await fetchInspectorSessionToken(baseUrl))
1575
+ );
1573
1576
  }
1574
1577
  return {
1575
1578
  baseUrl,
@@ -1598,7 +1601,9 @@ async function ensureInspector(options = {}) {
1598
1601
  );
1599
1602
  const url = buildInspectorUrl(browserBaseUrl2, options.tab);
1600
1603
  if (options.openBrowser) {
1601
- openUrl(url);
1604
+ openUrl(
1605
+ buildInspectorAccessUrl(url, await fetchInspectorSessionToken(baseUrl))
1606
+ );
1602
1607
  }
1603
1608
  return {
1604
1609
  baseUrl,
@@ -1752,7 +1757,7 @@ var InspectorApiClient = class {
1752
1757
  }
1753
1758
  throw operationalError("Inspector command response was invalid.", payload);
1754
1759
  }
1755
- async request(path9, init = {}) {
1760
+ async request(path11, init = {}) {
1756
1761
  const fetchRequest = async () => {
1757
1762
  const token = await fetchInspectorSessionToken(this.baseUrl);
1758
1763
  const { body: initBody, timeoutMs, ...fetchInit } = init;
@@ -1763,7 +1768,7 @@ var InspectorApiClient = class {
1763
1768
  headers.set("Content-Type", "application/json");
1764
1769
  body = JSON.stringify(initBody);
1765
1770
  }
1766
- return await fetch(`${this.baseUrl}${path9}`, {
1771
+ return await fetch(`${this.baseUrl}${path11}`, {
1767
1772
  ...fetchInit,
1768
1773
  signal: fetchInit.signal ?? AbortSignal.timeout(timeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS),
1769
1774
  headers,
@@ -1786,7 +1791,7 @@ var InspectorApiClient = class {
1786
1791
  const payload = await readResponsePayload(response);
1787
1792
  if (!response.ok && !init.treatAsSuccess?.(response.status, payload)) {
1788
1793
  throw operationalError(
1789
- getErrorMessage(payload) ?? `Inspector request ${path9} failed with ${response.status}.`,
1794
+ getErrorMessage(payload) ?? `Inspector request ${path11} failed with ${response.status}.`,
1790
1795
  payload
1791
1796
  );
1792
1797
  }
@@ -1822,9 +1827,36 @@ function clearInspectorSessionTokenCache(baseUrl) {
1822
1827
  tokenRequests.delete(normalizedBaseUrl);
1823
1828
  }
1824
1829
  async function fetchFreshInspectorSessionToken(normalizedBaseUrl) {
1830
+ const endpoint = new URL(normalizedBaseUrl);
1831
+ if (!isLoopbackHostname(endpoint.hostname))
1832
+ throw operationalError("Inspector attachment requires a local address.");
1833
+ let token;
1834
+ try {
1835
+ const file = path7.join(
1836
+ os.homedir(),
1837
+ ".mcpjam",
1838
+ "inspector",
1839
+ `${endpoint.port || "6274"}.json`
1840
+ );
1841
+ const stat2 = lstatSync(file);
1842
+ if (!stat2.isFile() || process.platform !== "win32" && ((stat2.mode & 63) !== 0 || stat2.uid !== process.getuid?.()))
1843
+ throw new Error("Unsafe discovery file permissions");
1844
+ const record = JSON.parse(readFileSync(file, "utf8"));
1845
+ if (record.port !== Number(endpoint.port || "6274") || !Number.isSafeInteger(record.pid) || record.pid <= 0 || typeof record.token !== "string" || !/^[A-Za-z0-9_-]{24,}$/.test(record.token))
1846
+ throw new Error("Invalid discovery file");
1847
+ process.kill(record.pid, 0);
1848
+ token = record.token;
1849
+ } catch {
1850
+ throw operationalError(
1851
+ "Cannot read this Inspector's access file. Start or restart an updated Inspector as the same user, then try again."
1852
+ );
1853
+ }
1825
1854
  let response;
1826
1855
  try {
1827
1856
  response = await fetch(`${normalizedBaseUrl}/api/session-token`, {
1857
+ headers: {
1858
+ "X-MCP-Session-Auth": `Bearer ${token}`
1859
+ },
1828
1860
  signal: AbortSignal.timeout(SESSION_TOKEN_TIMEOUT_MS)
1829
1861
  });
1830
1862
  } catch (error) {
@@ -1839,14 +1871,14 @@ async function fetchFreshInspectorSessionToken(normalizedBaseUrl) {
1839
1871
  );
1840
1872
  }
1841
1873
  const body = await response.json();
1842
- if (typeof body.token !== "string" || !body.token) {
1874
+ if (body.ok !== true) {
1843
1875
  throw operationalError("Inspector session-token response was invalid.");
1844
1876
  }
1845
1877
  tokenCache.set(normalizedBaseUrl, {
1846
- token: body.token,
1878
+ token,
1847
1879
  fetchedAt: Date.now()
1848
1880
  });
1849
- return body.token;
1881
+ return token;
1850
1882
  }
1851
1883
  function getInspectorStartScriptPath() {
1852
1884
  try {
@@ -1888,7 +1920,7 @@ async function isInspectorFrontendUrl(baseUrl) {
1888
1920
  return false;
1889
1921
  }
1890
1922
  const body = await response.text();
1891
- return hasInspectorFrontendMarker(body) || /<title>\s*MCPJam Inspector\s*<\/title>/i.test(body) || body.includes("/mcp_jam.svg") || body.includes("__MCP_SESSION_TOKEN__");
1923
+ return hasInspectorFrontendMarker(body) || /<title>\s*MCPJam Inspector\s*<\/title>/i.test(body) || body.includes("/mcp_jam.svg");
1892
1924
  } catch {
1893
1925
  return false;
1894
1926
  }
@@ -2070,6 +2102,7 @@ async function startInspector(baseUrl, timeoutMs) {
2070
2102
  stdio: ["ignore", logFd, logFd],
2071
2103
  env: {
2072
2104
  ...process.env,
2105
+ MCPJAM_SESSION_TOKEN: process.env.MCPJAM_SESSION_TOKEN ?? randomBytes(24).toString("base64url"),
2073
2106
  HOST: parsedUrl.hostname,
2074
2107
  MCPJAM_INSPECTOR_SUPPRESS_AUTO_OPEN: "1"
2075
2108
  }
@@ -2165,6 +2198,15 @@ function isInspectorCommandResponse(value) {
2165
2198
  error && typeof error === "object" && typeof error.code === "string" && typeof error.message === "string"
2166
2199
  );
2167
2200
  }
2201
+ function buildInspectorAccessUrl(url, token) {
2202
+ const target = new URL(url);
2203
+ const tab = target.hash.slice(1);
2204
+ target.hash = new URLSearchParams({
2205
+ token,
2206
+ ...tab ? { tab } : {}
2207
+ }).toString();
2208
+ return target.href;
2209
+ }
2168
2210
 
2169
2211
  // src/lib/inspector-render.ts
2170
2212
  async function runUiRender(options) {
@@ -4193,7 +4235,24 @@ function webOriginForApiBaseUrl(baseUrl) {
4193
4235
  function ciOwnedSuiteReason(details) {
4194
4236
  return typeof details === "object" && details !== null && details.reason === "CI_OWNED_SUITE_READ_ONLY";
4195
4237
  }
4196
- function toCliError(error) {
4238
+ function withRequestId(details, requestId) {
4239
+ return requestId ? { ...details ?? {}, requestId } : details;
4240
+ }
4241
+ var REPORTABLE_ERROR_CODES = /* @__PURE__ */ new Set([
4242
+ "INTERNAL_ERROR",
4243
+ "FEATURE_NOT_SUPPORTED"
4244
+ ]);
4245
+ var GATEWAY_FAILURE_STATUSES = /* @__PURE__ */ new Set([502, 503, 504]);
4246
+ var FEEDBACK_COMMAND = "cloud feedback";
4247
+ function feedbackHint(error, command) {
4248
+ if (command === FEEDBACK_COMMAND) return void 0;
4249
+ if (!error.requestId) return void 0;
4250
+ if (!REPORTABLE_ERROR_CODES.has(error.code)) return void 0;
4251
+ if (GATEWAY_FAILURE_STATUSES.has(error.status)) return void 0;
4252
+ const kind = error.code === "FEATURE_NOT_SUPPORTED" ? "missing_capability" : "bug";
4253
+ return `Report it: \`mcpjam cloud feedback --kind ${kind} --request-id ${error.requestId} --summary "\u2026"\``;
4254
+ }
4255
+ function toCliError(error, context = {}) {
4197
4256
  if (error instanceof CliError) {
4198
4257
  return error;
4199
4258
  }
@@ -4203,7 +4262,7 @@ function toCliError(error) {
4203
4262
  "CI_OWNED_SUITE_READ_ONLY",
4204
4263
  `${error.message} If this run is syncing a suite file, make sure the file's \`suite.id\` still matches the suite it created \u2014 a renamed id no longer owns it.`,
4205
4264
  1,
4206
- error.details
4265
+ withRequestId(error.details, error.requestId)
4207
4266
  );
4208
4267
  }
4209
4268
  const refusal = describePlatformRefusal(error);
@@ -4212,11 +4271,17 @@ function toCliError(error) {
4212
4271
  error.code,
4213
4272
  `${error.message} ${platformRefusalHint(refusal)}`,
4214
4273
  1,
4215
- { ...error.details ?? {}, refusal }
4274
+ withRequestId({ ...error.details ?? {}, refusal }, error.requestId)
4216
4275
  );
4217
4276
  }
4218
- const message = error.code === "UNAUTHORIZED" ? `${error.message} Run \`mcpjam cloud login\` or pass a valid sk_ API key.` : error.message;
4219
- return cliError(error.code, message, 1, error.details);
4277
+ const hint = feedbackHint(error, context.command);
4278
+ const message = error.code === "UNAUTHORIZED" ? `${error.message} Run \`mcpjam cloud login\` or pass a valid sk_ API key.` : hint ? `${error.message} ${hint}` : error.message;
4279
+ return cliError(
4280
+ error.code,
4281
+ message,
4282
+ 1,
4283
+ withRequestId(error.details, error.requestId)
4284
+ );
4220
4285
  }
4221
4286
  return cliError(
4222
4287
  "INTERNAL_ERROR",
@@ -4448,9 +4513,9 @@ async function runPlatformOperation(options, timeoutMs, execute, extras = {}) {
4448
4513
  return await execute({ ...context, signal: controller.signal });
4449
4514
  } catch (error) {
4450
4515
  if (controller.signal.aborted && controller.signal.reason instanceof PlatformApiError) {
4451
- throw toCliError(controller.signal.reason);
4516
+ throw toCliError(controller.signal.reason, { command: extras.command });
4452
4517
  }
4453
- const mapped = toCliError(error);
4518
+ const mapped = toCliError(error, { command: extras.command });
4454
4519
  throw new CliError(
4455
4520
  mapped.code,
4456
4521
  appendProjectLinkHint(mapped.message, extras.projectScope),
@@ -4472,6 +4537,13 @@ function hasCloudAncestor(command) {
4472
4537
  }
4473
4538
  return false;
4474
4539
  }
4540
+ function commandPathOf(command) {
4541
+ const names = [];
4542
+ for (let current = command; current?.parent; current = current.parent) {
4543
+ names.unshift(current.name());
4544
+ }
4545
+ return names.join(" ");
4546
+ }
4475
4547
  function commandHasProjectOption(command) {
4476
4548
  return command.options.some((option) => option.long === "--project");
4477
4549
  }
@@ -4493,7 +4565,7 @@ function bindOperation(command, operation, buildInput, bindExtras = {}) {
4493
4565
  const globalOptions = getGlobalOptions(invoked, bindExtras.defaultTimeoutMs);
4494
4566
  const merged = platformOptionsOf(invoked);
4495
4567
  const underCloud = hasCloudAncestor(invoked);
4496
- const applyAmbient = (underCloud || bindExtras.ambientProject === true) && commandHasProjectOption(invoked);
4568
+ const applyAmbient = bindExtras.ambientProject !== false && (underCloud || bindExtras.ambientProject === true) && commandHasProjectOption(invoked);
4497
4569
  const resolved = applyAmbient ? resolveCloudProjectArgs({ project: merged.project }) : void 0;
4498
4570
  const inputOptions = resolved ? { ...options, project: resolved.project } : options;
4499
4571
  let permalinks = [];
@@ -4530,6 +4602,7 @@ function bindOperation(command, operation, buildInput, bindExtras = {}) {
4530
4602
  {
4531
4603
  announce: bindExtras.announce ?? underCloud,
4532
4604
  quiet: globalOptions.quiet,
4605
+ command: commandPathOf(invoked),
4533
4606
  ...resolved ? {
4534
4607
  projectScope: resolved.projectScope,
4535
4608
  cloudScope: resolved.projectScope
@@ -5598,7 +5671,7 @@ async function validateImportToolReferences(client, params) {
5598
5671
  return { targets, findings };
5599
5672
  }
5600
5673
  function finding(reference, parts) {
5601
- const path9 = [
5674
+ const path11 = [
5602
5675
  "cases",
5603
5676
  reference.caseIndex,
5604
5677
  "steps",
@@ -5607,8 +5680,8 @@ function finding(reference, parts) {
5607
5680
  ];
5608
5681
  return {
5609
5682
  code: parts.code,
5610
- path: path9,
5611
- pointer: suiteFilePointer(path9),
5683
+ path: path11,
5684
+ pointer: suiteFilePointer(path11),
5612
5685
  caseId: reference.testCase.id,
5613
5686
  caseTitle: reference.testCase.title,
5614
5687
  toolName: reference.step.toolName,
@@ -5739,11 +5812,11 @@ function screenshotFilename(shot, index) {
5739
5812
  return `${tool}-${suffix}.png`;
5740
5813
  }
5741
5814
  var UNSUPPORTED_SUITE_EXPORT = "UNSUPPORTED_SUITE_EXPORT";
5742
- function unsupported(path9, message) {
5815
+ function unsupported(path11, message) {
5743
5816
  return {
5744
5817
  code: UNSUPPORTED_SUITE_EXPORT,
5745
- path: path9,
5746
- pointer: suiteFilePointer(path9),
5818
+ path: path11,
5819
+ pointer: suiteFilePointer(path11),
5747
5820
  message
5748
5821
  };
5749
5822
  }
@@ -5884,14 +5957,13 @@ function suiteLevelFindings(detail, cases, environment) {
5884
5957
  )
5885
5958
  );
5886
5959
  }
5887
- } else if (settings.minimumAccuracy === null || settings.minimumAccuracy === void 0) {
5888
- findings.push(
5889
- unsupported(
5890
- ["settings", "minimumAccuracy"],
5891
- "suite sets no minimum accuracy, and `defaults.passThreshold` is required in a suite file. Set one and export again."
5892
- )
5893
- );
5894
- } else if (settings.minimumAccuracy < 0 || settings.minimumAccuracy > 100 || percentToFraction(settings.minimumAccuracy) === null) {
5960
+ } else if (
5961
+ // A legacy suite with no minimum accuracy is NOT unset: every legacy
5962
+ // producer grades it at `LEGACY_SUITE_WIDE_THRESHOLD_PERCENT` (100, "every
5963
+ // unit must pass"), so exporting that value is lossless. Only a present
5964
+ // value that does not convert cleanly is refused.
5965
+ typeof settings.minimumAccuracy === "number" && (settings.minimumAccuracy < 0 || settings.minimumAccuracy > 100 || percentToFraction(settings.minimumAccuracy) === null)
5966
+ ) {
5895
5967
  findings.push(
5896
5968
  unsupported(
5897
5969
  ["settings", "minimumAccuracy"],
@@ -6030,15 +6102,15 @@ function hoistProvider(cases) {
6030
6102
  )
6031
6103
  };
6032
6104
  }
6033
- function differences(expected, actual, path9 = [], out = []) {
6105
+ function differences(expected, actual, path11 = [], out = []) {
6034
6106
  if (isDeepStrictEqual(expected, actual)) return out;
6035
6107
  const before = out.length;
6036
6108
  if (Array.isArray(expected) && Array.isArray(actual)) {
6037
6109
  const length = Math.max(expected.length, actual.length);
6038
6110
  for (let index = 0; index < length; index += 1) {
6039
- differences(expected[index], actual[index], [...path9, index], out);
6111
+ differences(expected[index], actual[index], [...path11, index], out);
6040
6112
  }
6041
- if (out.length === before) out.push(path9);
6113
+ if (out.length === before) out.push(path11);
6042
6114
  return out;
6043
6115
  }
6044
6116
  const bothObjects = expected !== null && actual !== null && typeof expected === "object" && typeof actual === "object" && !Array.isArray(expected) && !Array.isArray(actual);
@@ -6053,14 +6125,14 @@ function differences(expected, actual, path9 = [], out = []) {
6053
6125
  differences(
6054
6126
  expected[key],
6055
6127
  actual[key],
6056
- [...path9, key],
6128
+ [...path11, key],
6057
6129
  out
6058
6130
  );
6059
6131
  }
6060
- if (out.length === before) out.push(path9);
6132
+ if (out.length === before) out.push(path11);
6061
6133
  return out;
6062
6134
  }
6063
- out.push(path9);
6135
+ out.push(path11);
6064
6136
  return out;
6065
6137
  }
6066
6138
  function buildSuiteFileFromPlatform(input, options = {}) {
@@ -6142,9 +6214,10 @@ function buildSuiteFileFromPlatform(input, options = {}) {
6142
6214
  // A v2 suite uses its own fraction; a legacy one converts its percent.
6143
6215
  // Never the other way round for a v2 suite: `suiteLevelFindings` has
6144
6216
  // already refused the export when a v2 threshold is unreadable, so this
6145
- // `??` can only reach the legacy branch for a legacy suite.
6217
+ // `??` can only reach the legacy branch for a legacy suite. A legacy
6218
+ // suite with no percent writes the fallback every run already grades at.
6146
6219
  passThreshold: isVerdictPolicyV2Suite(detail.settings) ? suiteVerdictPolicyThreshold(detail.settings) : percentToFraction(
6147
- detail.settings.minimumAccuracy
6220
+ detail.settings.minimumAccuracy ?? LEGACY_SUITE_WIDE_THRESHOLD_PERCENT
6148
6221
  ),
6149
6222
  // `{}`, not the resolved defaults: the contract documents them and the
6150
6223
  // loader applies them, and writing them here would put values nobody
@@ -6193,8 +6266,8 @@ function buildSuiteFileFromPlatform(input, options = {}) {
6193
6266
  return {
6194
6267
  ok: false,
6195
6268
  findings: lost.map(
6196
- (path9) => unsupported(
6197
- path9,
6269
+ (path11) => unsupported(
6270
+ path11,
6198
6271
  `the suite file contract does not carry this value, so exporting would drop it. Nothing was written.`
6199
6272
  )
6200
6273
  )
@@ -6367,7 +6440,7 @@ function refuseUnsupportedHostedSemantics(loaded) {
6367
6440
  if (loaded.authored.defaults.toolPolicy !== void 0) {
6368
6441
  throw cliError(
6369
6442
  "TOOL_POLICY_UNSUPPORTED",
6370
- "defaults.toolPolicy is not representable on a hosted run. The platform would execute the unrestricted tool set while stamping this file's hash. Remove toolPolicy, or run the suite locally.",
6443
+ "defaults.toolPolicy is not representable on a hosted run. The platform would execute the unrestricted tool set while stamping this file's hash. Remove toolPolicy, or run the suite locally with `mcpjam test <file>`, which enforces it.",
6371
6444
  SUITE_FILE_RUN_INVALID_EXIT_CODE
6372
6445
  );
6373
6446
  }
@@ -7932,57 +8005,6 @@ function classifyWaitErrorExitCode(code) {
7932
8005
  if (code !== void 0 && AUTH_SHAPED_CODES.has(code)) return 3;
7933
8006
  return 5;
7934
8007
  }
7935
- function iterationLabel(iteration) {
7936
- const title = iteration.title?.trim();
7937
- return title ? `${title} #${iteration.iterationNumber}` : `iteration #${iteration.iterationNumber} (${iteration.id})`;
7938
- }
7939
- function formatIterationProvenance(runs) {
7940
- const lines = [];
7941
- for (const run of runs) {
7942
- if (run.error !== void 0) {
7943
- lines.push(
7944
- `Iteration provenance (run ${run.runId}): unavailable \u2014 ${run.error}`
7945
- );
7946
- continue;
7947
- }
7948
- if (run.iterations.length === 0) continue;
7949
- lines.push(`Iteration provenance (run ${run.runId}):`);
7950
- const ordered = [...run.iterations].sort(
7951
- (a, b) => (a.title ?? "").localeCompare(b.title ?? "") || a.iterationNumber - b.iterationNumber
7952
- );
7953
- for (const iteration of ordered) {
7954
- const record = readExecutionRecord(iteration.execution);
7955
- if (!record) {
7956
- lines.push(` ${iterationLabel(iteration)}: not recorded`);
7957
- continue;
7958
- }
7959
- lines.push(
7960
- ` ${iterationLabel(iteration)}: ${formatExecutionProvenanceLine(
7961
- record
7962
- )}`
7963
- );
7964
- if (record.deviation) {
7965
- lines.push(` ${formatExecutionDeviationLine(record.deviation)}`);
7966
- }
7967
- }
7968
- }
7969
- return lines;
7970
- }
7971
- function writeIterationProvenance(format, runs, stream = process.stdout) {
7972
- if (format !== "human") return;
7973
- const lines = formatIterationProvenance(runs);
7974
- if (lines.length === 0) return;
7975
- stream.write(`${lines.join("\n")}
7976
- `);
7977
- }
7978
- function formatRecordedExecutionDisclosure(model) {
7979
- if (model.provenance !== "execution-record" || !model.recorded) return null;
7980
- const { records, resolvedRails, attemptedRails, deviations } = model.recorded;
7981
- const extraRails = attemptedRails.filter(
7982
- (rail) => !resolvedRails.includes(rail)
7983
- );
7984
- return `Recorded (${records} record${records === 1 ? "" : "s"}): ran via ${resolvedRails.map(executionRailLabel).join(", ") || "no rail recorded"}` + (extraRails.length > 0 ? `; also attempted ${extraRails.map(executionRailLabel).join(", ")}` : "") + (deviations.length > 0 ? `; deviations: ${deviations.map(executionDeviationTitle).join(", ")}` : "");
7985
- }
7986
8008
  function decisionSummaryFromIterations(input) {
7987
8009
  return buildEvalRunDecisionSummary({
7988
8010
  projectId: input.projectId,
@@ -8226,8 +8248,6 @@ function writeRunDisclosure(format, disclosure, stream = process.stdout) {
8226
8248
  for (const model of execution.models) {
8227
8249
  const destination = model.byok?.baseUrlHost ? model.byok.baseUrlHost : model.rail.managed ? `${model.rail.possibleDestinations.join(" or ")} (currently: ${model.rail.outcomeIfRunNow.destination})` : model.tenantEgress;
8228
8250
  lines.push(` Model: ${model.modelId} \u2014 ${destination}`);
8229
- const recorded = formatRecordedExecutionDisclosure(model);
8230
- if (recorded) lines.push(` ${recorded}`);
8231
8251
  }
8232
8252
  } else if (execution.modelsUnresolved) {
8233
8253
  lines.push(
@@ -10237,34 +10257,11 @@ function registerEvalCommands(program) {
10237
10257
  result.project.id,
10238
10258
  runs[0]
10239
10259
  ) : void 0;
10240
- const provenance = globalOptions.format === "human" ? await Promise.all(
10241
- runs.map(async (run) => {
10242
- try {
10243
- const iterations = await fetchAllIterations(
10244
- client,
10245
- signal,
10246
- result.project.id,
10247
- run.id
10248
- );
10249
- return {
10250
- runId: run.id,
10251
- iterations: iterations.items
10252
- };
10253
- } catch (error) {
10254
- return {
10255
- runId: run.id,
10256
- iterations: [],
10257
- error: error instanceof Error ? error.message : String(error)
10258
- };
10259
- }
10260
- })
10261
- ) : [];
10262
10260
  return {
10263
10261
  runs,
10264
10262
  waitErrors,
10265
10263
  reportInputs: [],
10266
10264
  iterationErrorCodes: /* @__PURE__ */ new Map(),
10267
- provenance,
10268
10265
  ...soloSummary ? { decisionSummary: soloSummary } : {}
10269
10266
  };
10270
10267
  }
@@ -10310,14 +10307,6 @@ function registerEvalCommands(program) {
10310
10307
  waitErrors,
10311
10308
  reportInputs,
10312
10309
  iterationErrorCodes,
10313
- // Free: the walk the report already paid for.
10314
- provenance: reportInputs.map(
10315
- (input) => ({
10316
- runId: input.run.id,
10317
- iterations: input.iterations,
10318
- ...input.iterationError !== void 0 ? { error: input.iterationError } : {}
10319
- })
10320
- ),
10321
10310
  ...decisionSummary ? { decisionSummary } : {}
10322
10311
  };
10323
10312
  },
@@ -10379,11 +10368,6 @@ function registerEvalCommands(program) {
10379
10368
  }
10380
10369
  if (reporter && report) {
10381
10370
  writeReporterResult(reporter, report);
10382
- writeIterationProvenance(
10383
- globalOptions.format,
10384
- completion.provenance,
10385
- process.stderr
10386
- );
10387
10371
  } else {
10388
10372
  writeResult(
10389
10373
  {
@@ -10408,11 +10392,6 @@ function registerEvalCommands(program) {
10408
10392
  completion.decisionSummary,
10409
10393
  process.stdout
10410
10394
  );
10411
- writeIterationProvenance(
10412
- globalOptions.format,
10413
- completion.provenance,
10414
- process.stdout
10415
- );
10416
10395
  }
10417
10396
  if (outWriteError !== void 0) {
10418
10397
  throw cliError("OUT_WRITE_FAILED", outWriteError, worstOf([code, 4]));
@@ -11143,15 +11122,15 @@ function registerEvalCommands(program) {
11143
11122
  shot.screenshotUrl,
11144
11123
  globalOptions.timeout
11145
11124
  );
11146
- const path9 = resolveScreenshotPath(
11125
+ const path11 = resolveScreenshotPath(
11147
11126
  options.out,
11148
11127
  shot,
11149
11128
  i,
11150
11129
  shots.length
11151
11130
  );
11152
- mkdirSync(dirname(path9), { recursive: true });
11153
- writeFileSync(path9, bytes);
11154
- saved.push({ ...shot, savedTo: path9 });
11131
+ mkdirSync(dirname(path11), { recursive: true });
11132
+ writeFileSync(path11, bytes);
11133
+ saved.push({ ...shot, savedTo: path11 });
11155
11134
  }
11156
11135
  let video;
11157
11136
  if (options.video) {
@@ -11707,6 +11686,88 @@ ${summary}
11707
11686
  }
11708
11687
  );
11709
11688
  }
11689
+ function readDetails(path11) {
11690
+ try {
11691
+ return path11 === "-" ? readFileSync(0, "utf8") : readFileSync(path11, "utf8");
11692
+ } catch (error) {
11693
+ throw usageError(
11694
+ path11 === "-" ? "Failed to read --details from stdin." : `Failed to read --details from "${path11}".`,
11695
+ { source: error instanceof Error ? error.message : String(error) }
11696
+ );
11697
+ }
11698
+ }
11699
+ function buildFeedbackInput(options) {
11700
+ if (options.details !== void 0 && options.detailsFile !== void 0) {
11701
+ throw usageError("Pass --details or --details-file, not both.");
11702
+ }
11703
+ const details = options.detailsFile !== void 0 ? readDetails(options.detailsFile) : options.details;
11704
+ const parsed = sendFeedbackOperation.inputSchema.safeParse({
11705
+ kind: options.kind,
11706
+ summary: options.summary,
11707
+ ...details !== void 0 ? { details } : {},
11708
+ ...options.operation !== void 0 ? { operation: options.operation } : {},
11709
+ ...options.requestId !== void 0 ? { requestId: options.requestId } : {},
11710
+ ...options.errorCode !== void 0 ? { errorCode: options.errorCode } : {},
11711
+ ...options.project !== void 0 ? { project: options.project } : {},
11712
+ ...options.idempotencyKey !== void 0 ? { idempotencyKey: options.idempotencyKey } : {}
11713
+ });
11714
+ if (!parsed.success) {
11715
+ throw usageError(
11716
+ `Invalid input: ${parsed.error.issues.map(
11717
+ (issue) => issue.path.length > 0 ? `${issue.path.join(".")}: ${issue.message}` : issue.message
11718
+ ).join("; ")}`
11719
+ );
11720
+ }
11721
+ return parsed.data;
11722
+ }
11723
+ function formatReceipt(receipt) {
11724
+ return receipt.duplicate ? `Already received, thanks. An identical report is on file (${receipt.id}).` : `Sent to the MCPJam team (${receipt.id}). Thanks.`;
11725
+ }
11726
+ function registerFeedbackCommand(cloud) {
11727
+ const command = cloud.command("feedback").description(
11728
+ "Send feedback about MCPJam itself (a bug, a missing capability, something confusing) to the MCPJam team. Your text is sent to the MCPJam team, outside your organization, and stored for 180 days. Requires a signed-in account."
11729
+ ).requiredOption(
11730
+ "--kind <kind>",
11731
+ "bug, missing_capability, confusing, docs, or other"
11732
+ ).requiredOption(
11733
+ "--summary <text>",
11734
+ "One line: what went wrong or what is missing (up to 200 characters)."
11735
+ ).option(
11736
+ "--details <text>",
11737
+ "What you were trying to accomplish, what you expected, and what blocked you. For a missing capability, name the task and any workaround you tried. Up to 8000 characters. Never paste secrets, tokens, or raw tool output."
11738
+ ).option(
11739
+ "--details-file <path>",
11740
+ "Read --details from a file, or `-` for stdin."
11741
+ ).option(
11742
+ "--operation <name>",
11743
+ "The command, tool or app page in use (e.g. `cloud eval run`)."
11744
+ ).option(
11745
+ "--request-id <id>",
11746
+ "The request id from a failing command's error, so the report can be matched to the server's logs."
11747
+ ).option(
11748
+ "--error-code <code>",
11749
+ "The failing command's error code (e.g. INTERNAL_ERROR)."
11750
+ ).option(
11751
+ "--project <id-or-name>",
11752
+ "A project the report is about. Omit it otherwise: no project is assumed, not even a linked one."
11753
+ ).option(
11754
+ "--idempotency-key <key>",
11755
+ "Retry key: a retry with the same key returns the original receipt instead of filing the report twice."
11756
+ );
11757
+ bindOperation(
11758
+ command,
11759
+ sendFeedbackOperation,
11760
+ (options) => buildFeedbackInput(options),
11761
+ {
11762
+ // No project unless named: not the MCPJAM_PROJECT one, not the repo's
11763
+ // link. A report about the CLI filed against the linked project is
11764
+ // misfiled.
11765
+ ambientProject: false,
11766
+ cloudScope: { kind: "account" },
11767
+ formatHuman: formatReceipt
11768
+ }
11769
+ );
11770
+ }
11710
11771
  var CLIENT_TEMPLATES = HOST_TEMPLATES.map(({ id, label }) => ({ id, label }));
11711
11772
  function selectorOf(options) {
11712
11773
  if (options.client !== void 0 && options.host !== void 0) {
@@ -13482,12 +13543,12 @@ function resolveSecretValue(options, { required }) {
13482
13543
  }
13483
13544
  return value;
13484
13545
  }
13485
- const readStdinOrFile = (path9) => {
13546
+ const readStdinOrFile = (path11) => {
13486
13547
  try {
13487
- return path9 === "-" ? readFileSync(0, "utf8") : readFileSync(path9, "utf8");
13548
+ return path11 === "-" ? readFileSync(0, "utf8") : readFileSync(path11, "utf8");
13488
13549
  } catch (error) {
13489
13550
  throw usageError(
13490
- path9 === "-" ? "Failed to read the secret value from stdin." : `Failed to read the secret value from "${path9}".`,
13551
+ path11 === "-" ? "Failed to read the secret value from stdin." : `Failed to read the secret value from "${path11}".`,
13491
13552
  { source: error instanceof Error ? error.message : String(error) }
13492
13553
  );
13493
13554
  }
@@ -13873,15 +13934,15 @@ function registerSessionsBrowserCommands(sessions) {
13873
13934
  const extension = bytes[0] === 255 && bytes[1] === 216 ? "jpg" : "png";
13874
13935
  const dir = resolve(download);
13875
13936
  await mkdir(dir, { recursive: true });
13876
- const path9 = resolve(
13937
+ const path11 = resolve(
13877
13938
  dir,
13878
13939
  `${(wire.commandId ?? "screenshot").replace(
13879
13940
  /[^A-Za-z0-9_.-]/g,
13880
13941
  "_"
13881
13942
  )}.${extension}`
13882
13943
  );
13883
- await writeFile(path9, bytes);
13884
- return { ...result, savedTo: path9 };
13944
+ await writeFile(path11, bytes);
13945
+ return { ...result, savedTo: path11 };
13885
13946
  }
13886
13947
  },
13887
13948
  (o) => {
@@ -14709,8 +14770,8 @@ function resolveHeaders(options) {
14709
14770
  put(name, value, "--header-env");
14710
14771
  }
14711
14772
  for (const raw of options.headerFile ?? []) {
14712
- const [name, path9] = splitOnFirst(raw, "=", "--header-file");
14713
- const target = path9.trim();
14773
+ const [name, path11] = splitOnFirst(raw, "=", "--header-file");
14774
+ const target = path11.trim();
14714
14775
  let contents;
14715
14776
  try {
14716
14777
  contents = target === "-" ? readFileSync(0, "utf8") : readFileSync(target, "utf8");
@@ -16119,6 +16180,8 @@ function registerCloudCommands(program) {
16119
16180
  const goals = registerGoalsCommands(cloud);
16120
16181
  registerSwarmAuthoringCommands(cloud, goals);
16121
16182
  registerStudiesCommands(cloud);
16183
+ cloud.commandsGroup("Support:");
16184
+ registerFeedbackCommand(cloud);
16122
16185
  return cloud;
16123
16186
  }
16124
16187
  function resolveHostConnection(hostId) {
@@ -16145,25 +16208,7 @@ function resolveHostFromOptions(options) {
16145
16208
  return resolveHostConnection(options.host);
16146
16209
  }
16147
16210
  function applyHostToConfig(config, host) {
16148
- const identity2 = {
16149
- ...host.clientInfo ? { clientInfo: host.clientInfo } : {},
16150
- ...host.clientCapabilities ? { clientCapabilities: host.clientCapabilities } : {},
16151
- ...host.supportedProtocolVersions ? { supportedProtocolVersions: host.supportedProtocolVersions } : {}
16152
- };
16153
- const httpOnly = "url" in config ? {
16154
- ...host.mcpProtocolVersion ? { mcpProtocolVersion: host.mcpProtocolVersion } : {},
16155
- ...host.mirrorToolParamHeaders === false ? { mirrorToolParamHeaders: false } : {}
16156
- } : {};
16157
- const conformance = {
16158
- ...host.firstPageOnly ? { firstPageOnly: true } : {},
16159
- ...host.supportsMrtr === false ? { supportsMrtr: false } : {}
16160
- };
16161
- return {
16162
- ...config,
16163
- ...identity2,
16164
- ...httpOnly,
16165
- ...conformance
16166
- };
16211
+ return applyHostConnectionProfile(config, host);
16167
16212
  }
16168
16213
  function applyHostVisibility(tools, manager, serverId, policy) {
16169
16214
  const record = {};
@@ -17985,13 +18030,13 @@ function resolveFixtures(options) {
17985
18030
  }
17986
18031
  return { toolCalls, promptGets };
17987
18032
  }
17988
- function readFixturesFile(path9) {
18033
+ function readFixturesFile(path11) {
17989
18034
  let raw;
17990
18035
  try {
17991
- raw = readFileSync(path9, "utf8");
18036
+ raw = readFileSync(path11, "utf8");
17992
18037
  } catch (error) {
17993
18038
  throw usageError(
17994
- `Could not read fixtures file ${path9}: ${error instanceof Error ? error.message : String(error)}`
18039
+ `Could not read fixtures file ${path11}: ${error instanceof Error ? error.message : String(error)}`
17995
18040
  );
17996
18041
  }
17997
18042
  let parsed;
@@ -17999,15 +18044,15 @@ function readFixturesFile(path9) {
17999
18044
  parsed = JSON.parse(raw);
18000
18045
  } catch (error) {
18001
18046
  throw usageError(
18002
- `Fixtures file ${path9} is not valid JSON: ${error instanceof Error ? error.message : String(error)}`
18047
+ `Fixtures file ${path11} is not valid JSON: ${error instanceof Error ? error.message : String(error)}`
18003
18048
  );
18004
18049
  }
18005
18050
  if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {
18006
18051
  throw usageError(
18007
- `Fixtures file ${path9} must contain a JSON object with toolCalls and/or promptGets`
18052
+ `Fixtures file ${path11} must contain a JSON object with toolCalls and/or promptGets`
18008
18053
  );
18009
18054
  }
18010
- validateFixtures(parsed, `Fixtures file ${path9}`);
18055
+ validateFixtures(parsed, `Fixtures file ${path11}`);
18011
18056
  const document = parsed;
18012
18057
  return {
18013
18058
  toolCalls: document.toolCalls ?? [],
@@ -18283,17 +18328,17 @@ function requestHeaders(options, target) {
18283
18328
  if (token) headers.authorization = `Bearer ${token}`;
18284
18329
  return Object.keys(headers).length > 0 ? headers : void 0;
18285
18330
  }
18286
- async function openPackage(path9) {
18331
+ async function openPackage(path11) {
18287
18332
  let info;
18288
18333
  try {
18289
- info = await stat(path9);
18334
+ info = await stat(path11);
18290
18335
  } catch {
18291
- throw usageError(`Package path "${path9}" does not exist.`);
18336
+ throw usageError(`Package path "${path11}" does not exist.`);
18292
18337
  }
18293
18338
  if (info.isDirectory()) {
18294
- return { source: createDirectoryPluginFileSource(path9) };
18339
+ return { source: createDirectoryPluginFileSource(path11) };
18295
18340
  }
18296
- const bytes = new Uint8Array(await readFile(path9));
18341
+ const bytes = new Uint8Array(await readFile(path11));
18297
18342
  return {
18298
18343
  source: await createZipPluginFileSource(bytes),
18299
18344
  // The RAW central directory, read before the zip library normalizes it:
@@ -23247,6 +23292,864 @@ function isCompactInspectorCommandStatus(value) {
23247
23292
  function isRecord4(value) {
23248
23293
  return Boolean(value && typeof value === "object" && !Array.isArray(value));
23249
23294
  }
23295
+ var PROVIDER_KEY_ENV_VARS = {
23296
+ anthropic: ["ANTHROPIC_API_KEY"],
23297
+ openai: ["OPENAI_API_KEY"],
23298
+ google: ["GOOGLE_GENERATIVE_AI_API_KEY", "GEMINI_API_KEY"],
23299
+ deepseek: ["DEEPSEEK_API_KEY"],
23300
+ mistral: ["MISTRAL_API_KEY"],
23301
+ openrouter: ["OPENROUTER_API_KEY"],
23302
+ xai: ["XAI_API_KEY"]
23303
+ };
23304
+ function readProviderKeys(env) {
23305
+ const keys = {};
23306
+ for (const [provider, names] of Object.entries(PROVIDER_KEY_ENV_VARS)) {
23307
+ for (const name of names) {
23308
+ const value = env[name]?.trim();
23309
+ if (value) {
23310
+ keys[provider] = value;
23311
+ break;
23312
+ }
23313
+ }
23314
+ }
23315
+ return keys;
23316
+ }
23317
+ function trimTrailingSlashes(value) {
23318
+ let end = value.length;
23319
+ while (end > 0 && value[end - 1] === "/") end -= 1;
23320
+ return value.slice(0, end);
23321
+ }
23322
+ function baseUrlFromEnv(env, name, normalize = (url) => trimTrailingSlashes(url.href)) {
23323
+ const raw = env[name]?.trim();
23324
+ if (!raw) return void 0;
23325
+ let url;
23326
+ try {
23327
+ url = new URL(raw);
23328
+ } catch {
23329
+ throw usageError(
23330
+ `${name} must be a URL (received ${JSON.stringify(raw)}).`
23331
+ );
23332
+ }
23333
+ return normalize(url);
23334
+ }
23335
+ function readProviderBaseUrls(env) {
23336
+ const openai = baseUrlFromEnv(env, "OPENAI_BASE_URL");
23337
+ const anthropic = baseUrlFromEnv(env, "ANTHROPIC_BASE_URL", (url) => {
23338
+ const trimmed2 = trimTrailingSlashes(url.href);
23339
+ return /\/v1$/.test(trimmed2) ? trimmed2 : `${trimmed2}/v1`;
23340
+ });
23341
+ const ollama = baseUrlFromEnv(env, "OLLAMA_BASE_URL");
23342
+ return {
23343
+ ...openai ? { openai } : {},
23344
+ ...anthropic ? { anthropic } : {},
23345
+ ...ollama ? { ollama } : {}
23346
+ };
23347
+ }
23348
+ function appBaseFromApiBase(apiBaseUrl) {
23349
+ const trimmed2 = trimTrailingSlashes(apiBaseUrl);
23350
+ return trimmed2.replace(/\/api\/v1$/, "");
23351
+ }
23352
+ function refusalFromCliError(error) {
23353
+ if (error.exitCode === 2) {
23354
+ return new SuiteFileRunError({
23355
+ code: "OPTIONS_INVALID",
23356
+ phase: "setup",
23357
+ category: "usage",
23358
+ message: error.message
23359
+ });
23360
+ }
23361
+ return new SuiteFileRunError({
23362
+ code: "CREDENTIALS_MISSING",
23363
+ phase: "setup",
23364
+ category: "credentials",
23365
+ message: error.message
23366
+ });
23367
+ }
23368
+ function createMcpjamConnectionResolver(options, deps) {
23369
+ return async (signal) => {
23370
+ const active = signal ?? deps.signal;
23371
+ const warned = /* @__PURE__ */ new Set();
23372
+ const warn = (message) => {
23373
+ if (warned.has(message)) return;
23374
+ warned.add(message);
23375
+ (deps.warn ?? ((line2) => process.stderr.write(`${line2}
23376
+ `)))(
23377
+ message
23378
+ );
23379
+ };
23380
+ const credentialDeps = {
23381
+ env: deps.env,
23382
+ warn,
23383
+ ...deps.authFilePath ? { authFilePath: deps.authFilePath } : {},
23384
+ ...deps.fetchFn ? { fetchFn: deps.fetchFn } : {}
23385
+ };
23386
+ let built;
23387
+ let credential;
23388
+ let headers;
23389
+ let selector;
23390
+ try {
23391
+ built = buildPlatformClient(
23392
+ {
23393
+ ...options.apiKey ? { apiKey: options.apiKey } : {},
23394
+ ...options.apiUrl ? { apiUrl: options.apiUrl } : {},
23395
+ ...options.apiHeader ? { apiHeader: options.apiHeader } : {},
23396
+ timeoutMs: deps.timeoutMs
23397
+ },
23398
+ credentialDeps
23399
+ );
23400
+ credential = resolvePlatformCredential(
23401
+ options.apiKey ? { apiKey: options.apiKey } : {},
23402
+ credentialDeps
23403
+ );
23404
+ headers = resolvePlatformExtraHeaders(
23405
+ options.apiHeader ? { apiHeader: options.apiHeader } : {},
23406
+ deps.env
23407
+ );
23408
+ selector = resolveCloudProjectArgs(
23409
+ options.project ? { project: options.project } : {}
23410
+ ).project;
23411
+ } catch (error) {
23412
+ if (error instanceof CliError) throw refusalFromCliError(error);
23413
+ throw error;
23414
+ }
23415
+ let projects;
23416
+ try {
23417
+ projects = await built.client.listProjects(
23418
+ {},
23419
+ active ? { signal: active } : {}
23420
+ );
23421
+ } catch (error) {
23422
+ if (error instanceof CliError) throw refusalFromCliError(error);
23423
+ if (isPlatformApiError(error)) {
23424
+ const auth = error.status === 401 || error.status === 403 || ["UNAUTHORIZED", "FORBIDDEN", "OAUTH_REQUIRED"].includes(error.code);
23425
+ throw new SuiteFileRunError({
23426
+ code: auth ? "CREDENTIALS_REJECTED" : "PLATFORM_UNAVAILABLE",
23427
+ phase: "setup",
23428
+ category: auth ? "credentials" : "setup",
23429
+ message: `MCPJam rejected the request to resolve a project: ${error.message}`
23430
+ });
23431
+ }
23432
+ throw new SuiteFileRunError({
23433
+ code: "PLATFORM_UNAVAILABLE",
23434
+ phase: "setup",
23435
+ category: "setup",
23436
+ message: `Could not reach MCPJam to resolve a project: ${error instanceof Error ? error.message : String(error)}`
23437
+ });
23438
+ }
23439
+ const resolution = resolveProject(projects.items, selector);
23440
+ if (!resolution.ok) {
23441
+ throw new SuiteFileRunError({
23442
+ code: "OPTIONS_INVALID",
23443
+ phase: "setup",
23444
+ category: "usage",
23445
+ message: resolution.message
23446
+ });
23447
+ }
23448
+ return {
23449
+ baseUrl: appBaseFromApiBase(built.baseUrl),
23450
+ projectId: resolution.project.id,
23451
+ getAuth: () => credential.getAuth(),
23452
+ ...headers ? { headers } : {}
23453
+ };
23454
+ };
23455
+ }
23456
+ var SETUP_EXIT_CODE = 4;
23457
+ function parseServerOverride(raw) {
23458
+ const index = raw.indexOf("=");
23459
+ if (index < 1) {
23460
+ throw usageError(
23461
+ `--server must be "name=url" (received ${JSON.stringify(raw)}).`
23462
+ );
23463
+ }
23464
+ const name = raw.slice(0, index).trim();
23465
+ const url = raw.slice(index + 1).trim();
23466
+ if (!name) {
23467
+ throw usageError(`--server ${JSON.stringify(raw)} has no server name.`);
23468
+ }
23469
+ let parsed;
23470
+ try {
23471
+ parsed = new URL(url);
23472
+ } catch {
23473
+ throw usageError(`--server ${name}: ${JSON.stringify(url)} is not a URL.`);
23474
+ }
23475
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
23476
+ throw usageError(
23477
+ `--server ${name}: only http(s) URLs can be overridden on the command line; bind stdio servers with an MCP config.`
23478
+ );
23479
+ }
23480
+ return { name, url };
23481
+ }
23482
+ var INTERPOLATION = /\$\{([A-Za-z_][A-Za-z0-9_]*)(:-([^}]*))?\}/g;
23483
+ function interpolate(value, env, missing) {
23484
+ return value.replace(
23485
+ INTERPOLATION,
23486
+ (_match, name, hasDefault, fallback) => {
23487
+ const current = env[name];
23488
+ if (hasDefault !== void 0) {
23489
+ return current !== void 0 && current !== "" ? current : fallback ?? "";
23490
+ }
23491
+ if (current === void 0) {
23492
+ missing.add(name);
23493
+ return "";
23494
+ }
23495
+ return current;
23496
+ }
23497
+ );
23498
+ }
23499
+ function readConfigMap(source) {
23500
+ if (!existsSync(source.filePath)) {
23501
+ if (!source.required) return void 0;
23502
+ throw cliError(
23503
+ "MCP_CONFIG_UNREADABLE",
23504
+ `MCP config ${source.filePath} does not exist.`,
23505
+ SETUP_EXIT_CODE
23506
+ );
23507
+ }
23508
+ let raw;
23509
+ try {
23510
+ raw = JSON.parse(readFileSync(source.filePath, "utf8"));
23511
+ } catch (error) {
23512
+ throw cliError(
23513
+ "MCP_CONFIG_INVALID",
23514
+ `MCP config ${source.filePath} is not valid JSON: ${error instanceof Error ? error.message : String(error)}`,
23515
+ SETUP_EXIT_CODE
23516
+ );
23517
+ }
23518
+ const selection = selectPluginMcpServerMap(raw);
23519
+ if (!selection.ok) {
23520
+ throw cliError(
23521
+ "MCP_CONFIG_INVALID",
23522
+ `MCP config ${source.filePath}: ${selection.message}.`,
23523
+ SETUP_EXIT_CODE
23524
+ );
23525
+ }
23526
+ return new Map(selection.servers.map((entry) => [entry.key, entry.config]));
23527
+ }
23528
+ function isRecord5(value) {
23529
+ return typeof value === "object" && value !== null && !Array.isArray(value);
23530
+ }
23531
+ function stringRecord(value, what, where) {
23532
+ if (value === void 0) return void 0;
23533
+ if (!isRecord5(value)) {
23534
+ throw cliError(
23535
+ "MCP_CONFIG_INVALID",
23536
+ `${where}: ${what} must be an object of strings.`,
23537
+ SETUP_EXIT_CODE
23538
+ );
23539
+ }
23540
+ const out = {};
23541
+ for (const [key, entry] of Object.entries(value)) {
23542
+ if (typeof entry !== "string") {
23543
+ throw cliError(
23544
+ "MCP_CONFIG_INVALID",
23545
+ `${where}: ${what}.${key} must be a string.`,
23546
+ SETUP_EXIT_CODE
23547
+ );
23548
+ }
23549
+ out[key] = entry;
23550
+ }
23551
+ return out;
23552
+ }
23553
+ function configFromEntry(args) {
23554
+ const where = `server "${args.name}" in ${args.source.filePath}`;
23555
+ const detected = detectPluginMcpTransport(args.entry, args.name);
23556
+ if (!detected.ok) {
23557
+ throw cliError(
23558
+ "MCP_CONFIG_INVALID",
23559
+ `${args.source.filePath}: ${detected.message}.`,
23560
+ SETUP_EXIT_CODE
23561
+ );
23562
+ }
23563
+ const entry = args.entry;
23564
+ const configDir = path7.dirname(args.source.filePath);
23565
+ const missing = /* @__PURE__ */ new Set();
23566
+ const expand = (value) => interpolate(value, args.env, missing);
23567
+ let config;
23568
+ if (detected.transport === "stdio") {
23569
+ if (typeof entry.command !== "string" || entry.command.trim() === "") {
23570
+ throw cliError(
23571
+ "MCP_CONFIG_INVALID",
23572
+ `${where}: "command" must be a non-empty string.`,
23573
+ SETUP_EXIT_CODE
23574
+ );
23575
+ }
23576
+ if (entry.args !== void 0 && (!Array.isArray(entry.args) || entry.args.some((arg) => typeof arg !== "string"))) {
23577
+ throw cliError(
23578
+ "MCP_CONFIG_INVALID",
23579
+ `${where}: "args" must be an array of strings.`,
23580
+ SETUP_EXIT_CODE
23581
+ );
23582
+ }
23583
+ if (entry.cwd !== void 0 && typeof entry.cwd !== "string") {
23584
+ throw cliError(
23585
+ "MCP_CONFIG_INVALID",
23586
+ `${where}: "cwd" must be a string.`,
23587
+ SETUP_EXIT_CODE
23588
+ );
23589
+ }
23590
+ const envEntries = stringRecord(entry.env, "env", where);
23591
+ const cwd = typeof entry.cwd === "string" ? expand(entry.cwd) : void 0;
23592
+ config = {
23593
+ command: expand(entry.command),
23594
+ ...Array.isArray(entry.args) ? { args: entry.args.map(expand) } : {},
23595
+ ...envEntries ? {
23596
+ env: Object.fromEntries(
23597
+ Object.entries(envEntries).map(([key, value]) => [
23598
+ key,
23599
+ expand(value)
23600
+ ])
23601
+ )
23602
+ } : {},
23603
+ // A relative `cwd` belongs to the file that declared it; an absent one
23604
+ // is where the command was invoked.
23605
+ cwd: cwd !== void 0 ? path7.resolve(configDir, cwd) : args.invocationCwd,
23606
+ stderr: "pipe",
23607
+ timeout: args.requestTimeoutMs
23608
+ };
23609
+ } else {
23610
+ if (typeof entry.url !== "string" || entry.url.trim() === "") {
23611
+ throw cliError(
23612
+ "MCP_CONFIG_INVALID",
23613
+ `${where}: "url" must be a non-empty string.`,
23614
+ SETUP_EXIT_CODE
23615
+ );
23616
+ }
23617
+ if (entry.credentialsFile !== void 0 && typeof entry.credentialsFile !== "string") {
23618
+ throw cliError(
23619
+ "MCP_CONFIG_INVALID",
23620
+ `${where}: "credentialsFile" must be a string.`,
23621
+ SETUP_EXIT_CODE
23622
+ );
23623
+ }
23624
+ const url = expand(entry.url);
23625
+ const headers = stringRecord(entry.headers, "headers", where);
23626
+ const expandedHeaders = headers ? Object.fromEntries(
23627
+ Object.entries(headers).map(([key, value]) => [key, expand(value)])
23628
+ ) : void 0;
23629
+ const declaredType = String(
23630
+ entry.type ?? entry.transport ?? ""
23631
+ ).toLowerCase();
23632
+ const credentialsPath = typeof entry.credentialsFile === "string" ? expand(entry.credentialsFile) : void 0;
23633
+ const credentials = credentialsPath !== void 0 && missing.size === 0 ? resolveCredentialsFileAuth(
23634
+ path7.resolve(configDir, credentialsPath),
23635
+ url
23636
+ ) : void 0;
23637
+ config = {
23638
+ url,
23639
+ ...expandedHeaders ? { requestInit: { headers: expandedHeaders } } : {},
23640
+ ...declaredType === "sse" ? { preferSSE: true } : {},
23641
+ ...credentials?.accessToken ? { accessToken: credentials.accessToken } : {},
23642
+ ...credentials?.refreshToken ? { refreshToken: credentials.refreshToken } : {},
23643
+ ...credentials?.clientId ? { clientId: credentials.clientId } : {},
23644
+ ...credentials?.clientSecret ? { clientSecret: credentials.clientSecret } : {},
23645
+ timeout: args.requestTimeoutMs
23646
+ };
23647
+ if (missing.size === 0) {
23648
+ try {
23649
+ new URL(url);
23650
+ } catch {
23651
+ throw cliError(
23652
+ "MCP_CONFIG_INVALID",
23653
+ `${where}: "url" is not a URL after interpolation.`,
23654
+ SETUP_EXIT_CODE
23655
+ );
23656
+ }
23657
+ }
23658
+ }
23659
+ if (missing.size > 0) {
23660
+ throw cliError(
23661
+ "MCP_CONFIG_INTERPOLATION",
23662
+ `${where} references unset environment variable(s): ${[...missing].join(
23663
+ ", "
23664
+ )}. Set them, or give a default with \${VAR:-default}.`,
23665
+ SETUP_EXIT_CODE,
23666
+ { server: args.name, variables: [...missing] }
23667
+ );
23668
+ }
23669
+ return config;
23670
+ }
23671
+ var SINGLE_SERVER_FLAGS = [
23672
+ ["transport", "--transport"],
23673
+ ["accessToken", "--access-token"],
23674
+ ["oauthAccessToken", "--oauth-access-token"],
23675
+ ["refreshToken", "--refresh-token"],
23676
+ ["clientId", "--client-id"],
23677
+ ["clientSecret", "--client-secret"],
23678
+ ["credentialsFile", "--credentials-file"],
23679
+ ["header", "--header"],
23680
+ ["clientCapabilities", "--client-capabilities"],
23681
+ ["args", "--args"],
23682
+ ["commandArgs", "--command-args"],
23683
+ ["env", "--env"],
23684
+ ["cwd", "--cwd"]
23685
+ ];
23686
+ function isSet(value) {
23687
+ if (typeof value === "string") return value.trim() !== "";
23688
+ if (Array.isArray(value)) return value.length > 0;
23689
+ return value !== void 0 && value !== null;
23690
+ }
23691
+ function resolveLocalServerBindings(input) {
23692
+ const targets = [...input.targetNames];
23693
+ const bindings = {};
23694
+ const overrides = /* @__PURE__ */ new Map();
23695
+ for (const raw of input.serverOverrides ?? []) {
23696
+ const override = parseServerOverride(raw);
23697
+ if (overrides.has(override.name)) {
23698
+ throw usageError(`--server names "${override.name}" more than once.`);
23699
+ }
23700
+ if (!targets.includes(override.name)) {
23701
+ throw usageError(
23702
+ `--server names "${override.name}", which the suite does not target (${targets.join(", ")}).`
23703
+ );
23704
+ }
23705
+ overrides.set(override.name, override.url);
23706
+ }
23707
+ const single = input.singleServer;
23708
+ const hasSingle = Boolean(single?.url?.trim() || single?.command?.trim());
23709
+ if (hasSingle) {
23710
+ if (targets.length !== 1) {
23711
+ throw usageError(
23712
+ `--url/--command bind exactly one server, and this suite targets ${targets.length}. Bind each with --server <name=url> or an MCP config entry; one credential is never shared across servers.`
23713
+ );
23714
+ }
23715
+ if (overrides.has(targets[0])) {
23716
+ throw usageError(
23717
+ `--server ${targets[0]} and --url/--command both bind "${targets[0]}"; pass one.`
23718
+ );
23719
+ }
23720
+ bindings[targets[0]] = {
23721
+ config: parseServerConfig({ ...single, timeout: input.requestTimeoutMs }),
23722
+ source: single?.url?.trim() ? "--url" : "--command"
23723
+ };
23724
+ } else {
23725
+ const inapplicable = SINGLE_SERVER_FLAGS.filter(
23726
+ ([key]) => isSet(single?.[key])
23727
+ ).map(([, flag]) => flag);
23728
+ if (inapplicable.length > 0) {
23729
+ throw usageError(
23730
+ `${inapplicable.join(", ")} ${inapplicable.length === 1 ? "applies" : "apply"} only to the one server bound with --url or --command. For servers bound with --server or an MCP config file, put headers, env, cwd, args and credentials in the config entry.`
23731
+ );
23732
+ }
23733
+ }
23734
+ for (const [name, url] of overrides) {
23735
+ bindings[name] = {
23736
+ config: { url, timeout: input.requestTimeoutMs },
23737
+ source: "--server"
23738
+ };
23739
+ }
23740
+ const sources = [
23741
+ ...input.mcpConfigPath ? [
23742
+ {
23743
+ label: "--mcp-config",
23744
+ filePath: path7.resolve(input.cwd, input.mcpConfigPath),
23745
+ required: true
23746
+ }
23747
+ ] : [],
23748
+ {
23749
+ label: ".mcp.json",
23750
+ filePath: path7.resolve(input.cwd, ".mcp.json"),
23751
+ required: false
23752
+ },
23753
+ {
23754
+ label: ".mcpjam/mcp.json",
23755
+ filePath: path7.resolve(input.cwd, ".mcpjam", "mcp.json"),
23756
+ required: false
23757
+ }
23758
+ ];
23759
+ for (const source of sources) {
23760
+ const unresolved = targets.filter((name) => bindings[name] === void 0);
23761
+ if (unresolved.length === 0 && !source.required) break;
23762
+ const map = readConfigMap(source);
23763
+ if (!map) continue;
23764
+ for (const name of unresolved) {
23765
+ if (!map.has(name)) continue;
23766
+ bindings[name] = {
23767
+ config: configFromEntry({
23768
+ name,
23769
+ entry: map.get(name),
23770
+ source,
23771
+ env: input.env,
23772
+ invocationCwd: input.cwd,
23773
+ requestTimeoutMs: input.requestTimeoutMs
23774
+ }),
23775
+ source: source.label
23776
+ };
23777
+ }
23778
+ }
23779
+ const missing = targets.filter((name) => bindings[name] === void 0);
23780
+ if (missing.length > 0) {
23781
+ throw cliError(
23782
+ "SERVER_BINDING_MISSING",
23783
+ `No local configuration for target server(s): ${missing.join(", ")}. Bind each with --server <name=url>, --mcp-config <path>, or an entry in ./.mcp.json or ./.mcpjam/mcp.json.`,
23784
+ SETUP_EXIT_CODE,
23785
+ { missing }
23786
+ );
23787
+ }
23788
+ return Object.fromEntries(targets.map((name) => [name, bindings[name]]));
23789
+ }
23790
+
23791
+ // src/lib/local-test-exit-code.ts
23792
+ var LOCAL_TEST_EXIT = {
23793
+ passed: 0,
23794
+ failed: 1,
23795
+ usage: 2,
23796
+ credentials: 3,
23797
+ setup: 4,
23798
+ notEstablished: 5
23799
+ };
23800
+ var USAGE_CATEGORIES = /* @__PURE__ */ new Set([
23801
+ "usage",
23802
+ "unsupported",
23803
+ "import",
23804
+ "policy"
23805
+ ]);
23806
+ function localTestExitCodeForError(error) {
23807
+ if (USAGE_CATEGORIES.has(error.category)) return LOCAL_TEST_EXIT.usage;
23808
+ switch (error.category) {
23809
+ case "credentials":
23810
+ return LOCAL_TEST_EXIT.credentials;
23811
+ case "billing":
23812
+ case "setup":
23813
+ return LOCAL_TEST_EXIT.setup;
23814
+ case "cancelled":
23815
+ case "integrity":
23816
+ return LOCAL_TEST_EXIT.notEstablished;
23817
+ default:
23818
+ return error.phase === "validation" || error.phase === "setup" ? LOCAL_TEST_EXIT.setup : LOCAL_TEST_EXIT.notEstablished;
23819
+ }
23820
+ }
23821
+ function localTestExitCodeForResult(result, observed = {}) {
23822
+ const codes = [];
23823
+ switch (result.verdict) {
23824
+ case "passed":
23825
+ codes.push(LOCAL_TEST_EXIT.passed);
23826
+ break;
23827
+ case "failed":
23828
+ codes.push(LOCAL_TEST_EXIT.failed);
23829
+ break;
23830
+ default:
23831
+ codes.push(LOCAL_TEST_EXIT.notEstablished);
23832
+ }
23833
+ for (const issue of result.issues) {
23834
+ if (issue.category === "credentials")
23835
+ codes.push(LOCAL_TEST_EXIT.credentials);
23836
+ else if (issue.category === "billing" || issue.category === "setup") {
23837
+ codes.push(LOCAL_TEST_EXIT.setup);
23838
+ } else if (issue.category === "integrity" || issue.category === "internal") {
23839
+ codes.push(LOCAL_TEST_EXIT.notEstablished);
23840
+ }
23841
+ }
23842
+ if (observed.artifactWriteFailed) codes.push(LOCAL_TEST_EXIT.setup);
23843
+ return worstOf(codes);
23844
+ }
23845
+
23846
+ // src/commands/test.ts
23847
+ function collect2(value, previous = []) {
23848
+ return [...previous, value];
23849
+ }
23850
+ function parseLocalApprovals(options) {
23851
+ const parsed = parseApprovalFlags(options);
23852
+ return parsed?.cases.map((caseId) => ({ caseId, reason: parsed.reason }));
23853
+ }
23854
+ function parseInferenceMode(value) {
23855
+ const mode = (value ?? "auto").trim();
23856
+ if (mode === "auto" || mode === "byok" || mode === "mcpjam") return mode;
23857
+ throw usageError(
23858
+ `--inference must be auto, byok or mcpjam (received ${JSON.stringify(
23859
+ value
23860
+ )}).`
23861
+ );
23862
+ }
23863
+ function readSuiteFile(filePath, cwd) {
23864
+ const resolvedPath = path7.resolve(cwd, filePath);
23865
+ let bytes;
23866
+ try {
23867
+ bytes = readFileSync(resolvedPath);
23868
+ } catch (error) {
23869
+ throw usageError(
23870
+ `Cannot read suite file ${resolvedPath}: ${error instanceof Error ? error.message : String(error)}`
23871
+ );
23872
+ }
23873
+ try {
23874
+ return {
23875
+ text: new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(
23876
+ bytes
23877
+ ),
23878
+ resolvedPath
23879
+ };
23880
+ } catch {
23881
+ throw usageError(`Suite file ${resolvedPath} is not valid UTF-8.`);
23882
+ }
23883
+ }
23884
+ function progressWriter(quiet) {
23885
+ return (event) => {
23886
+ if (quiet) return;
23887
+ switch (event.type) {
23888
+ case "setup":
23889
+ if (event.stage === "connect" && event.server) {
23890
+ process.stderr.write(`Connecting to ${event.server}\u2026
23891
+ `);
23892
+ } else if (event.stage === "lease" && event.model) {
23893
+ process.stderr.write(
23894
+ `Preparing MCPJam inference for ${event.model}\u2026
23895
+ `
23896
+ );
23897
+ }
23898
+ return;
23899
+ case "caseStart":
23900
+ process.stderr.write(
23901
+ `Case ${event.index + 1}/${event.total}: ${event.caseId} (${event.iterations} iteration${event.iterations === 1 ? "" : "s"})
23902
+ `
23903
+ );
23904
+ return;
23905
+ default:
23906
+ return;
23907
+ }
23908
+ };
23909
+ }
23910
+ function isUnactionableAiSdkWarning(warning) {
23911
+ if (warning.type === "compatibility" && warning.feature === "specificationVersion") {
23912
+ return true;
23913
+ }
23914
+ return typeof warning.message === "string" && /is unknown\. The max output tokens have been limited to/.test(
23915
+ warning.message
23916
+ );
23917
+ }
23918
+ function routeAiSdkWarnings(quiet) {
23919
+ const holder = globalThis;
23920
+ const previous = holder.AI_SDK_LOG_WARNINGS;
23921
+ const seen = /* @__PURE__ */ new Set();
23922
+ holder.AI_SDK_LOG_WARNINGS = (log) => {
23923
+ if (quiet) return;
23924
+ for (const warning of log.warnings ?? []) {
23925
+ if (isUnactionableAiSdkWarning(warning)) continue;
23926
+ const text = warning.message ?? (warning.feature ? `"${warning.feature}" is not supported${warning.details ? `: ${warning.details}` : ""}` : JSON.stringify(warning));
23927
+ const line2 = `Model warning (${log.provider ?? "provider"} / ${log.model ?? "model"}): ${text}`;
23928
+ if (seen.has(line2)) continue;
23929
+ seen.add(line2);
23930
+ process.stderr.write(`${line2}
23931
+ `);
23932
+ }
23933
+ };
23934
+ return () => {
23935
+ holder.AI_SDK_LOG_WARNINGS = previous;
23936
+ };
23937
+ }
23938
+ function refusalToCliError(error) {
23939
+ return cliError(error.code, error.message, localTestExitCodeForError(error), {
23940
+ phase: error.phase,
23941
+ category: error.category,
23942
+ ...error.details.problems ? { problems: error.details.problems } : {}
23943
+ });
23944
+ }
23945
+ function registerTestCommand(program, dependencies = {}) {
23946
+ const command = program.command("test").description(
23947
+ "Run a suite file locally against your MCP servers (BYOK or MCPJam-hosted inference). Results are never uploaded."
23948
+ ).argument(
23949
+ "<file>",
23950
+ "Suite file (YAML or JSON), e.g. .mcpjam/evals/example.yaml"
23951
+ ).option(
23952
+ "--case <id>",
23953
+ "Run only this case id (exact; repeatable)",
23954
+ collect2,
23955
+ []
23956
+ ).option(
23957
+ "--server <name=url>",
23958
+ "Bind a target server to an HTTP(S) URL (repeatable; wins over MCP config files)",
23959
+ collect2,
23960
+ []
23961
+ ).option(
23962
+ "--mcp-config <path>",
23963
+ "MCP JSON config to bind target servers from (before ./.mcp.json and ./.mcpjam/mcp.json)"
23964
+ ).option(
23965
+ "--host <template>",
23966
+ "Emulate this host template's handshake and settings (e.g. claude-code, chatgpt); never the real client"
23967
+ ).option("--inference <mode>", "auto (default), byok, or mcpjam").option(
23968
+ "--allow-approximated <case>",
23969
+ "Approve an approximated imported case for this run (repeatable; needs --approval-reason)",
23970
+ collect2,
23971
+ []
23972
+ ).option(
23973
+ "--approval-reason <text>",
23974
+ "Why the approximated cases may run (1-500 characters)"
23975
+ ).option(
23976
+ "--concurrency <n>",
23977
+ "Iterations of one case in flight at once (default 1)"
23978
+ ).option(
23979
+ "--iteration-timeout <ms>",
23980
+ "Per-iteration execution timeout in milliseconds (default 120000)"
23981
+ ).option("--max-steps <n>", "Model steps per prompt (default 10)").option(
23982
+ "--reporter <format>",
23983
+ "Write a report to stdout: json-summary, junit-xml, or html"
23984
+ ).option(
23985
+ "--out <path>",
23986
+ "Write the report to this file (the --reporter format, or JSON)"
23987
+ );
23988
+ addProjectOption(addPlatformOptions(addSharedServerOptions(command)));
23989
+ command.action(
23990
+ async (file, options, cmd) => {
23991
+ const globalOptions = getGlobalOptions(cmd);
23992
+ const cwd = dependencies.cwd ?? process.cwd();
23993
+ const env = dependencies.env ?? process.env;
23994
+ const reporter = parseReporterFormat(
23995
+ options.reporter
23996
+ );
23997
+ const inferenceMode = parseInferenceMode(options.inference);
23998
+ if (options.host !== void 0) {
23999
+ resolveHostFromOptions({
24000
+ host: options.host,
24001
+ ...options.clientCapabilities !== void 0 ? { clientCapabilities: options.clientCapabilities } : {}
24002
+ });
24003
+ }
24004
+ const approvals = parseLocalApprovals(options);
24005
+ const concurrency = options.concurrency !== void 0 ? parsePositiveInteger(options.concurrency, "--concurrency") : void 0;
24006
+ const iterationTimeoutMs = options.iterationTimeout !== void 0 ? parsePositiveInteger(
24007
+ options.iterationTimeout,
24008
+ "--iteration-timeout"
24009
+ ) : void 0;
24010
+ const maxSteps = options.maxSteps !== void 0 ? parsePositiveInteger(options.maxSteps, "--max-steps") : void 0;
24011
+ const caseIds = options.case && options.case.length > 0 ? options.case : void 0;
24012
+ const { text } = readSuiteFile(file, cwd);
24013
+ const loaded = loadEvalSuiteFile(text);
24014
+ const targetNames = loaded.ok ? (loaded.resolved.target.servers ?? []).map((server) => server.name) : [];
24015
+ const controller = new AbortController();
24016
+ const onSignal = (signal) => {
24017
+ process.removeListener("SIGINT", onSignal);
24018
+ process.removeListener("SIGTERM", onSignal);
24019
+ if (!globalOptions.quiet) {
24020
+ process.stderr.write(
24021
+ `
24022
+ Received ${signal}; stopping and writing the partial report\u2026
24023
+ `
24024
+ );
24025
+ }
24026
+ controller.abort(new Error(`interrupted by ${signal}`));
24027
+ };
24028
+ process.on("SIGINT", onSignal);
24029
+ process.on("SIGTERM", onSignal);
24030
+ const restoreWarnings = routeAiSdkWarnings(globalOptions.quiet);
24031
+ let result;
24032
+ try {
24033
+ let servers = {};
24034
+ let bindingError;
24035
+ if (loaded.ok && targetNames.length > 0) {
24036
+ try {
24037
+ servers = resolveLocalServerBindings({
24038
+ targetNames,
24039
+ serverOverrides: options.server ?? [],
24040
+ ...options.mcpConfig ? { mcpConfigPath: options.mcpConfig } : {},
24041
+ singleServer: options,
24042
+ cwd,
24043
+ env,
24044
+ requestTimeoutMs: globalOptions.timeout
24045
+ });
24046
+ } catch (error) {
24047
+ if (!(error instanceof CliError) || error.exitCode === LOCAL_TEST_EXIT.usage) {
24048
+ throw error;
24049
+ }
24050
+ bindingError = error;
24051
+ }
24052
+ }
24053
+ const runOptions = {
24054
+ servers,
24055
+ ...caseIds ? { caseIds } : {},
24056
+ inference: {
24057
+ mode: inferenceMode,
24058
+ providerKeys: readProviderKeys(env),
24059
+ baseUrls: readProviderBaseUrls(env),
24060
+ resolveMcpjam: createMcpjamConnectionResolver(
24061
+ {
24062
+ ...options.apiKey ? { apiKey: options.apiKey } : {},
24063
+ ...options.apiUrl ? { apiUrl: options.apiUrl } : {},
24064
+ ...options.apiHeader ? { apiHeader: options.apiHeader } : {},
24065
+ ...options.project ? { project: options.project } : {}
24066
+ },
24067
+ {
24068
+ env,
24069
+ timeoutMs: globalOptions.timeout,
24070
+ signal: controller.signal
24071
+ }
24072
+ )
24073
+ },
24074
+ ...options.host !== void 0 ? { hostTemplateId: options.host } : {},
24075
+ ...approvals ? { importApprovals: approvals } : {},
24076
+ ...concurrency !== void 0 ? { concurrency } : {},
24077
+ ...iterationTimeoutMs !== void 0 ? { iterationTimeoutMs } : {},
24078
+ ...maxSteps !== void 0 ? { maxSteps } : {},
24079
+ setupTimeoutMs: globalOptions.timeout,
24080
+ signal: controller.signal,
24081
+ // Progress is always stderr, so stdout stays one document.
24082
+ onProgress: progressWriter(globalOptions.quiet)
24083
+ };
24084
+ const runner = dependencies.runtime ? createSuiteFileRunner(dependencies.runtime) : { run: runSuiteFile };
24085
+ try {
24086
+ result = await runner.run(text, runOptions);
24087
+ } catch (error) {
24088
+ if (error instanceof SuiteFileRunError) {
24089
+ if (bindingError && error.code === "SERVER_BINDING_MISSING")
24090
+ throw bindingError;
24091
+ throw refusalToCliError(error);
24092
+ }
24093
+ throw cliError(
24094
+ "INTERNAL_ERROR",
24095
+ error instanceof Error ? error.message : String(error),
24096
+ LOCAL_TEST_EXIT.setup
24097
+ );
24098
+ }
24099
+ } catch (error) {
24100
+ if (error instanceof CliError) {
24101
+ writeError(error, globalOptions.format);
24102
+ setProcessExitCode(error.exitCode);
24103
+ return;
24104
+ }
24105
+ throw error;
24106
+ } finally {
24107
+ process.removeListener("SIGINT", onSignal);
24108
+ process.removeListener("SIGTERM", onSignal);
24109
+ restoreWarnings();
24110
+ }
24111
+ let artifactWriteFailed = false;
24112
+ let artifactPath;
24113
+ try {
24114
+ if (options.out) {
24115
+ try {
24116
+ artifactPath = await writeReporterArtifact(
24117
+ path7.resolve(cwd, options.out),
24118
+ reporter ?? "json-summary",
24119
+ result.report
24120
+ );
24121
+ } catch (error) {
24122
+ artifactWriteFailed = true;
24123
+ writeError(error, globalOptions.format);
24124
+ }
24125
+ }
24126
+ const summary = formatLocalEvalRunSummary(result.report);
24127
+ if (reporter) {
24128
+ writeReporterResult(reporter, result.report);
24129
+ if (!globalOptions.quiet) process.stderr.write(`${summary}
24130
+ `);
24131
+ } else if (globalOptions.format === "json") {
24132
+ writeResult(renderStructuredRunJson(result.report), "json");
24133
+ } else {
24134
+ process.stdout.write(`${summary}
24135
+ `);
24136
+ }
24137
+ if (artifactPath && !globalOptions.quiet) {
24138
+ (reporter || globalOptions.format === "json" ? process.stderr : process.stdout).write(`Report written to ${artifactPath}
24139
+ `);
24140
+ }
24141
+ } catch (error) {
24142
+ writeError(error, globalOptions.format);
24143
+ setProcessExitCode(LOCAL_TEST_EXIT.notEstablished);
24144
+ return;
24145
+ }
24146
+ const exitCode = localTestExitCodeForResult(result, {
24147
+ artifactWriteFailed
24148
+ });
24149
+ setProcessExitCode(exitCode);
24150
+ }
24151
+ );
24152
+ }
23250
24153
 
23251
24154
  // src/commands/inspector.ts
23252
24155
  function addInspectorUrlOption(command) {
@@ -23474,7 +24377,7 @@ async function requireBrowserConsentCapability(client) {
23474
24377
  );
23475
24378
  }
23476
24379
  }
23477
- async function post(options, path9, body, timeoutMs) {
24380
+ async function post(options, path11, body, timeoutMs) {
23478
24381
  if (options.cloud) {
23479
24382
  if (options.inspectorUrl || options.consent)
23480
24383
  throw usageError(
@@ -23487,14 +24390,14 @@ async function post(options, path9, body, timeoutMs) {
23487
24390
  timeoutMs: timeoutMs ?? 12e4
23488
24391
  });
23489
24392
  return client2.browserSession(
23490
- path9.slice(1),
24393
+ path11.slice(1),
23491
24394
  body
23492
24395
  );
23493
24396
  }
23494
24397
  const client = new InspectorApiClient({ baseUrl: browserBaseUrl(options) });
23495
24398
  const consentToken = consentOf(options);
23496
24399
  await requireBrowserConsentCapability(client);
23497
- const result = await client.request(`${BROWSER_ROUTE}${path9}`, {
24400
+ const result = await client.request(`${BROWSER_ROUTE}${path11}`, {
23498
24401
  method: "POST",
23499
24402
  body,
23500
24403
  headers: { [BROWSER_CONSENT_HEADER]: consentToken },
@@ -24301,6 +25204,7 @@ async function main(argv = process.argv, dependencies = {}) {
24301
25204
  );
24302
25205
  const telemetry = initTelemetry(program, pkgVersion, dependencies.telemetry);
24303
25206
  program.commandsGroup("Local MCP testing:");
25207
+ registerTestCommand(program, dependencies.localTest);
24304
25208
  registerServerCommands(program);
24305
25209
  registerToolsCommands(program);
24306
25210
  registerResourcesCommands(program);