@githits/mcp 0.38.1 → 0.39.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/client.d.ts +37 -26
- package/dist/client.js +1 -1
- package/dist/index.d.ts +23 -12
- package/dist/index.js +7 -7
- package/dist/shared/{chunk-rk9w8cvk.js → chunk-54mxpkxp.js} +5 -5
- package/dist/shared/{chunk-m2pmp47r.js → chunk-k55ev4d4.js} +1 -1
- package/dist/shared/{chunk-rxe14jq0.js → chunk-yv5er0y7.js} +10 -4
- package/dist/smoke-test.js +1 -1
- package/dist/tools.d.ts +11 -11
- package/dist/tools.js +1 -1
- package/package.json +1 -1
package/dist/client.d.ts
CHANGED
|
@@ -28,20 +28,6 @@ interface CreateClientHeaderBuilderOptions {
|
|
|
28
28
|
*/
|
|
29
29
|
declare function createClientHeaderBuilder(options: CreateClientHeaderBuilderOptions): ClientHeaderBuilder;
|
|
30
30
|
/**
|
|
31
|
-
* Optional per-call progress correlation for backend requests.
|
|
32
|
-
*
|
|
33
|
-
* Progress is best effort: the HTTP result stays authoritative. The backend
|
|
34
|
-
* validates progress headers before admission, accounting and execution, so a
|
|
35
|
-
* rejection carrying `X-GitHits-Progress-Error` means nothing ran and the same
|
|
36
|
-
* request is safe to resend once without the progress headers.
|
|
37
|
-
*/
|
|
38
|
-
interface ProgressRequest {
|
|
39
|
-
/** Correlation headers merged after client headers and before auth. */
|
|
40
|
-
readonly headers: Readonly<Record<string, string>>;
|
|
41
|
-
/** Reports a pre-execution progress rejection; the call is then resent without progress. */
|
|
42
|
-
rejected(code: string): void;
|
|
43
|
-
}
|
|
44
|
-
/**
|
|
45
31
|
* Host-supplied diagnostics for transport-neutral service clients.
|
|
46
32
|
*
|
|
47
33
|
* Implementations may record operation timings or debug events in whatever
|
|
@@ -63,6 +49,17 @@ interface ServiceDiagnostics {
|
|
|
63
49
|
isEnabled(area: string): boolean;
|
|
64
50
|
debug(area: string, event: Record<string, unknown>): void;
|
|
65
51
|
}
|
|
52
|
+
/**
|
|
53
|
+
* Optional per-call controls shared by network-backed service methods.
|
|
54
|
+
*
|
|
55
|
+
* `signal` is the caller's cancellation signal, such as an MCP request
|
|
56
|
+
* cancellation. Services combine it with their own request deadline: a caller
|
|
57
|
+
* abort rejects with the signal's reason and is never retried, while an
|
|
58
|
+
* internal deadline keeps each service's timeout error mapping.
|
|
59
|
+
*/
|
|
60
|
+
interface ServiceRequestOptions {
|
|
61
|
+
signal?: AbortSignal;
|
|
62
|
+
}
|
|
66
63
|
interface TokenProvider {
|
|
67
64
|
/** Get a valid token, refreshing proactively or reactively as needed. */
|
|
68
65
|
getToken(): Promise<string | undefined>;
|
|
@@ -70,6 +67,20 @@ interface TokenProvider {
|
|
|
70
67
|
forceRefresh(): Promise<string | undefined>;
|
|
71
68
|
}
|
|
72
69
|
declare function createStaticTokenProvider(token: string): TokenProvider;
|
|
70
|
+
/**
|
|
71
|
+
* Optional per-call progress correlation for backend requests.
|
|
72
|
+
*
|
|
73
|
+
* Progress is best effort: the HTTP result stays authoritative. The backend
|
|
74
|
+
* validates progress headers before admission, accounting and execution, so a
|
|
75
|
+
* rejection carrying `X-GitHits-Progress-Error` means nothing ran and the same
|
|
76
|
+
* request is safe to resend once without the progress headers.
|
|
77
|
+
*/
|
|
78
|
+
interface ProgressRequest {
|
|
79
|
+
/** Correlation headers merged after client headers and before auth. */
|
|
80
|
+
readonly headers: Readonly<Record<string, string>>;
|
|
81
|
+
/** Reports a pre-execution progress rejection; the call is then resent without progress. */
|
|
82
|
+
rejected(code: string): void;
|
|
83
|
+
}
|
|
73
84
|
declare const AGENTIC_ASK_REQUEST_TIMEOUT_MS = 21e4;
|
|
74
85
|
interface AgenticAskQuestion {
|
|
75
86
|
question: string;
|
|
@@ -185,17 +196,6 @@ interface ReadTarget {
|
|
|
185
196
|
startLine?: number;
|
|
186
197
|
endLine?: number;
|
|
187
198
|
}
|
|
188
|
-
/**
|
|
189
|
-
* Optional per-call controls shared by network-backed service methods.
|
|
190
|
-
*
|
|
191
|
-
* `signal` is the caller's cancellation signal, such as an MCP request
|
|
192
|
-
* cancellation. Services combine it with their own request deadline: a caller
|
|
193
|
-
* abort rejects with the signal's reason and is never retried, while an
|
|
194
|
-
* internal deadline keeps each service's timeout error mapping.
|
|
195
|
-
*/
|
|
196
|
-
interface ServiceRequestOptions {
|
|
197
|
-
signal?: AbortSignal;
|
|
198
|
-
}
|
|
199
199
|
/** Nullable registry-version association carried by public error inventories. */
|
|
200
200
|
interface RecoveryRef {
|
|
201
201
|
ref: string;
|
|
@@ -1390,11 +1390,22 @@ interface RegistryRepository {
|
|
|
1390
1390
|
name: string;
|
|
1391
1391
|
url: string;
|
|
1392
1392
|
}
|
|
1393
|
+
/** Why the registry pointer is excluded from default release selection. */
|
|
1394
|
+
type RegistryLatestDifferenceReason = "DEPRECATED" | "YANKED" | "NO_FILES" | "UNLISTED" | "PRERELEASE_EXCLUDED";
|
|
1395
|
+
interface RegistryLatestDifference {
|
|
1396
|
+
version: string;
|
|
1397
|
+
reason: RegistryLatestDifferenceReason;
|
|
1398
|
+
}
|
|
1393
1399
|
interface PackageIdentity {
|
|
1394
1400
|
name: string;
|
|
1395
1401
|
registry?: string;
|
|
1396
1402
|
description?: string;
|
|
1397
|
-
|
|
1403
|
+
/** Release selected for this overview; absent when no release is selected. */
|
|
1404
|
+
version?: string;
|
|
1405
|
+
publishedAt?: string;
|
|
1406
|
+
registryLatestDifference?: RegistryLatestDifference;
|
|
1407
|
+
/** Registry pointer, which may differ from the selected release. */
|
|
1408
|
+
latestVersion?: string;
|
|
1398
1409
|
latestVersionPublishedAt?: string;
|
|
1399
1410
|
homepage?: string;
|
|
1400
1411
|
repositoryUrl?: string;
|
package/dist/client.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{GrepGraphQLError2,GrepBackendError2,GrepAccessError2,GrepNetworkError2,MalformedGrepResponseError2,GrepServiceImpl2,ListAccessError2,ListGraphQLError2,ListBackendError2,ListNetworkError2,MalformedListResponseError2,ListServiceImpl2,ReadServiceImpl2,RefreshingGitHitsService2,ResolveTargetServiceImpl2,createStaticTokenProvider2,SessionIdConfigError2,getEnvSessionId2,createClientHeaderBuilder2}from"./shared/chunk-
|
|
1
|
+
import{GrepGraphQLError2,GrepBackendError2,GrepAccessError2,GrepNetworkError2,MalformedGrepResponseError2,GrepServiceImpl2,ListAccessError2,ListGraphQLError2,ListBackendError2,ListNetworkError2,MalformedListResponseError2,ListServiceImpl2,ReadServiceImpl2,RefreshingGitHitsService2,ResolveTargetServiceImpl2,createStaticTokenProvider2,SessionIdConfigError2,getEnvSessionId2,createClientHeaderBuilder2}from"./shared/chunk-54mxpkxp.js";import{ProviderReauthenticationRequiredError2,DEFAULT_MCP_URL2,DEFAULT_API_URL2,DEFAULT_CODE_NAV_URL2,getMcpUrl2,getApiUrl2,getCodeNavigationUrl2,getEnvApiToken2,GitHitsServiceImpl2,AGENTIC_ASK_REQUEST_TIMEOUT_MS2,AgenticAskServiceImpl2,PKGSEER_REGISTRY_LIST2,toPkgseerRegistry2,toPkgseerRegistryLowercase2,CodeDiffError2,CodeNavigationServiceImpl2,PackageIntelligenceServiceImpl2}from"./shared/chunk-yv5er0y7.js";export{AGENTIC_ASK_REQUEST_TIMEOUT_MS2 as AGENTIC_ASK_REQUEST_TIMEOUT_MS,AgenticAskServiceImpl2 as AgenticAskServiceImpl,CodeDiffError2 as CodeDiffError,CodeNavigationServiceImpl2 as CodeNavigationServiceImpl,DEFAULT_API_URL2 as DEFAULT_API_URL,DEFAULT_CODE_NAV_URL2 as DEFAULT_CODE_NAV_URL,DEFAULT_MCP_URL2 as DEFAULT_MCP_URL,GitHitsServiceImpl2 as GitHitsServiceImpl,GrepAccessError2 as GrepAccessError,GrepBackendError2 as GrepBackendError,GrepGraphQLError2 as GrepGraphQLError,GrepNetworkError2 as GrepNetworkError,GrepServiceImpl2 as GrepServiceImpl,ListAccessError2 as ListAccessError,ListBackendError2 as ListBackendError,ListGraphQLError2 as ListGraphQLError,ListNetworkError2 as ListNetworkError,ListServiceImpl2 as ListServiceImpl,MalformedGrepResponseError2 as MalformedGrepResponseError,MalformedListResponseError2 as MalformedListResponseError,PKGSEER_REGISTRY_LIST2 as PKGSEER_REGISTRY_LIST,PackageIntelligenceServiceImpl2 as PackageIntelligenceServiceImpl,ProviderReauthenticationRequiredError2 as ProviderReauthenticationRequiredError,ReadServiceImpl2 as ReadServiceImpl,RefreshingGitHitsService2 as RefreshingGitHitsService,ResolveTargetServiceImpl2 as ResolveTargetServiceImpl,SessionIdConfigError2 as SessionIdConfigError,createClientHeaderBuilder2 as createClientHeaderBuilder,createStaticTokenProvider2 as createStaticTokenProvider,getApiUrl2 as getApiUrl,getCodeNavigationUrl2 as getCodeNavigationUrl,getEnvApiToken2 as getEnvApiToken,getEnvSessionId2 as getEnvSessionId,getMcpUrl2 as getMcpUrl,toPkgseerRegistry2 as toPkgseerRegistry,toPkgseerRegistryLowercase2 as toPkgseerRegistryLowercase};
|
package/dist/index.d.ts
CHANGED
|
@@ -20,6 +20,17 @@ declare function buildMcpQuickStart(options?: BuildMcpQuickStartOptions): string
|
|
|
20
20
|
declare function buildMcpInstructions(options?: BuildMcpInstructionsOptions): string;
|
|
21
21
|
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
22
22
|
/**
|
|
23
|
+
* Optional per-call controls shared by network-backed service methods.
|
|
24
|
+
*
|
|
25
|
+
* `signal` is the caller's cancellation signal, such as an MCP request
|
|
26
|
+
* cancellation. Services combine it with their own request deadline: a caller
|
|
27
|
+
* abort rejects with the signal's reason and is never retried, while an
|
|
28
|
+
* internal deadline keeps each service's timeout error mapping.
|
|
29
|
+
*/
|
|
30
|
+
interface ServiceRequestOptions {
|
|
31
|
+
signal?: AbortSignal;
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
23
34
|
* Optional per-call progress correlation for backend requests.
|
|
24
35
|
*
|
|
25
36
|
* Progress is best effort: the HTTP result stays authoritative. The backend
|
|
@@ -102,17 +113,6 @@ interface ReadTarget {
|
|
|
102
113
|
endLine?: number;
|
|
103
114
|
}
|
|
104
115
|
/**
|
|
105
|
-
* Optional per-call controls shared by network-backed service methods.
|
|
106
|
-
*
|
|
107
|
-
* `signal` is the caller's cancellation signal, such as an MCP request
|
|
108
|
-
* cancellation. Services combine it with their own request deadline: a caller
|
|
109
|
-
* abort rejects with the signal's reason and is never retried, while an
|
|
110
|
-
* internal deadline keeps each service's timeout error mapping.
|
|
111
|
-
*/
|
|
112
|
-
interface ServiceRequestOptions {
|
|
113
|
-
signal?: AbortSignal;
|
|
114
|
-
}
|
|
115
|
-
/**
|
|
116
116
|
* Back-compat alias — the canonical registry union now lives in
|
|
117
117
|
* `src/shared/pkgseer-registry.ts`. Re-exported here so existing
|
|
118
118
|
* consumers of `CodeNavigationRegistry` compile unchanged.
|
|
@@ -1061,11 +1061,22 @@ interface RegistryRepository {
|
|
|
1061
1061
|
name: string;
|
|
1062
1062
|
url: string;
|
|
1063
1063
|
}
|
|
1064
|
+
/** Why the registry pointer is excluded from default release selection. */
|
|
1065
|
+
type RegistryLatestDifferenceReason = "DEPRECATED" | "YANKED" | "NO_FILES" | "UNLISTED" | "PRERELEASE_EXCLUDED";
|
|
1066
|
+
interface RegistryLatestDifference {
|
|
1067
|
+
version: string;
|
|
1068
|
+
reason: RegistryLatestDifferenceReason;
|
|
1069
|
+
}
|
|
1064
1070
|
interface PackageIdentity {
|
|
1065
1071
|
name: string;
|
|
1066
1072
|
registry?: string;
|
|
1067
1073
|
description?: string;
|
|
1068
|
-
|
|
1074
|
+
/** Release selected for this overview; absent when no release is selected. */
|
|
1075
|
+
version?: string;
|
|
1076
|
+
publishedAt?: string;
|
|
1077
|
+
registryLatestDifference?: RegistryLatestDifference;
|
|
1078
|
+
/** Registry pointer, which may differ from the selected release. */
|
|
1079
|
+
latestVersion?: string;
|
|
1069
1080
|
latestVersionPublishedAt?: string;
|
|
1070
1081
|
homepage?: string;
|
|
1071
1082
|
repositoryUrl?: string;
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{DEFAULT_WAIT_TIMEOUT_MS,AuthenticationError2,ClientUpdateRequiredError,PKGSEER_REGISTRY_ARGS,PKGSEER_REGISTRY_LIST2,toPkgseerRegistry2,toPkgseerRegistryLowercase2,parsePkgseerRegistryArg,parseVersionRefRecovery,MalformedCodeNavigationResponseError,MalformedPackageIntelligenceResponseError}from"./shared/chunk-
|
|
1
|
+
import{DEFAULT_WAIT_TIMEOUT_MS,AuthenticationError2,ClientUpdateRequiredError,PKGSEER_REGISTRY_ARGS,PKGSEER_REGISTRY_LIST2,toPkgseerRegistry2,toPkgseerRegistryLowercase2,parsePkgseerRegistryArg,parseVersionRefRecovery,MalformedCodeNavigationResponseError,MalformedPackageIntelligenceResponseError}from"./shared/chunk-yv5er0y7.js";import{EXTERNAL_CONTENT_POSTURE,PKG_VULNS_GUARDRAIL,PKG_INFO_GUARDRAIL,PKG_CHANGELOG_GUARDRAIL,PKG_UPGRADE_REVIEW_GUARDRAIL,CODE_READ_GUARDRAIL,CODE_GREP_GUARDRAIL,SEARCH_GUARDRAIL,KNOWN_REGISTRIES,UnsupportedRegistryError,InvalidPackageSpecError,InvalidArgumentError,parsePackageSpec,isKnownRegistry,LegacyRepositoryRefError,isRepositoryTargetSpec,parseRepositoryTargetSpec,isCanonicalRepositoryUrl,formatRepositoryTarget,formatRepositoryTargetLabel,buildInvalidTargetSpecError,terminalWidth,sanitizeTerminalText,wrapTerminalProse,projectTargetResolution,buildTargetResolutionNotes,buildRetryCandidateLine,buildSuggestedRefsLine,buildResolutionFromRetryCandidates,formatTargetResolutionIdentity,buildSourceCorrespondenceNotes,buildSourceCorrespondenceNote,toCodeNavigationRegistry,AuthRequiredError,mapSessionIdError,mapTermsAcceptanceError,shellQuote,shellQuoteExact,mapVersionRefRecovery,withVersionRefRecovery,mapCodeNavigationError,buildUpdateRequiredError,serviceRequestArgs,MAX_WAIT_TIMEOUT_MS,MAX_DISCOVERY_WAIT_TIMEOUT_MS,MCP_READ_DEFAULT_SPAN,MCP_READ_MAX_SPAN,formatProvenanceRow,formatSourceRow,renderSourceSection,sameRepositoryCommit,resolutionSourceFacts,formatRequestedIndexingExplanation,renderResolutionDetails,formatRequestedProvenance,formatPreparationRow,renderPreparationSection,formatPreparationRetry,indexingWaitMs,withIndexingRetryAction,formatMappedErrorText,READ_ONLY_TOOL_ANNOTATIONS,OPEN_WORLD_READ_ONLY_TOOL_ANNOTATIONS,textResult,errorResult,withErrorHandling,mcpMappedErrorResult,addLocalMcpAuthAction,throwIfCallerCancellation,createGetExampleTool2,colors,colorize,highlight,highlightMatch,highlightRanges,dim,mapPackageIntelligenceError,formatCompactNumber,createResearchTool2,parseUnifiedSearchTargetSpec,createResolveTargetTool2}from"./shared/chunk-k55ev4d4.js";import{GrepGraphQLError2,GrepBackendError2,GrepAccessError2,GrepNetworkError2,MalformedGrepResponseError2,parseGrepResult,ListAccessError2,ListGraphQLError2,ListBackendError2,ListNetworkError2,MalformedListResponseError2}from"./shared/chunk-54mxpkxp.js";var GUIDE=`# GitHits
|
|
2
2
|
|
|
3
3
|
GitHits provides open-source code, documentation, examples, and package information for API usage, implementation, dependencies, vulnerabilities, and release comparisons.
|
|
4
4
|
|
|
@@ -94,22 +94,22 @@ ${bullets}`}));return lines.join(`
|
|
|
94
94
|
`)}if(!verbose)return"";if(conflicts.length>0){lines.push(colorize(`Conflicts (${conflicts.length}):`,"yellow",useColors));const nameWidth=Math.max(...conflicts.map((c)=>c.name.length));const sorted=[...conflicts].sort((a,b)=>a.name<b.name?-1:a.name>b.name?1:0);for(const c of sorted){if(c.requirements.length>0){lines.push(...wrapIssueEvidence(` ${c.name}: ${c.requiredVersions.join(", ")}`,terminalWidth));for(const line of formatConflictRequirements(c.requirements,{headerRegistry:payload.registry}).lines){lines.push(...wrapIssueEvidence(line,terminalWidth))}continue}const padded=`${c.name}:`.padEnd(nameWidth+2);lines.push(` ${padded} ${c.requiredVersions.join(", ")}`)}}if(cycles.length>0){if(conflicts.length>0)lines.push("");lines.push(colorize(`Circular dependencies (${cycles.length}):`,"red",useColors));for(const c of cycles)lines.push(` ${c.cycle.join(" -> ")}`)}return lines.join(`
|
|
95
95
|
`)}function formatGroupsBlock(payload,verbose,useColors){const groups=payload.groups;const lines=[];if(!groups||groups.items.length===0){lines.push(payload.filter?`No dependency groups matched lifecycle filter: ${payload.filter.lifecycles.join(", ")}.`:"No dependency groups available.");return lines.join(`
|
|
96
96
|
`)}const summary=summariseGroupsByLifecycle(groups.items);const groupNoun=groups.items.length===1?"group":"groups";lines.push("Dependency groups:");lines.push("");lines.push(colorize(`${groups.items.length} ${groupNoun} (${summary}):`,"bold",useColors));lines.push("");if(verbose&&groups.environmentMarkers&&groups.environmentMarkers.length>0){lines.push(dim(`environmentMarkers (${groups.environmentMarkers.length}):`,useColors));for(const marker of groups.environmentMarkers){lines.push(dim(` ${formatEnvironmentMarker(marker)}`,useColors))}lines.push("")}for(const group of groups.items){const heading=formatGroupHeading(group,payload.registry);lines.push(` ${colorize(heading,"bold",useColors)}`);if(verbose){const metaLines=formatGroupMeta(group);for(const meta of metaLines){lines.push(` ${dim(meta,useColors)}`)}}const deps=sortAlphabetically(dedupeGroupItems(group.items),(d)=>d.name);if(deps.length===0){lines.push(` ${dim("(no dependencies)",useColors)}`)}else{const nameWidth=Math.max(...deps.map((d)=>d.name.length));for(const dep of deps){lines.push(` ${formatGroupDependencyRow(dep,group,payload,nameWidth)}`)}}lines.push("")}return lines.join(`
|
|
97
|
-
`).trimEnd()}function formatGroupDependencyRow(dep,group,payload,nameWidth){const constraint=dep.constraint??"";if(group.lifecycle!=="runtime"){const name=dep.name.padEnd(nameWidth);return`${name} ${constraint}`.trimEnd()}const resolvedVersion=payload.runtime?.items.find((item)=>item.name===dep.name)?.version;if(!resolvedVersion){const name=dep.name.padEnd(nameWidth);return`${name} ${constraint}`.trimEnd()}const versionedName=`${dep.name}@${resolvedVersion}`.padEnd(nameWidth);return`${versionedName} ${constraint}`.trimEnd()}function formatEnvironmentMarker(marker){if(marker.type&&marker.value)return`${marker.type}: ${marker.value}`;if(marker.value)return marker.value;if(marker.type)return marker.type;return marker.raw??"(empty marker)"}function formatGroupHeading(group,registry){if(group.conditionType==="always"){return group.name}const displayCondition=displayConditionType(group.conditionType,registry);const showValue=group.conditionValue!==undefined&&group.conditionValue.toLowerCase()!==group.name.toLowerCase();const tail=showValue?`${displayCondition}: ${group.conditionValue}`:displayCondition;return`${group.name} (${group.lifecycle}, ${tail})`}function displayConditionType(conditionType,registry){if(conditionType==="feature"&®istry==="pypi")return"extra";return conditionType}function formatGroupMeta(group){const rows=[];if(group.selectionMode!=="required"){rows.push(`selectionMode: ${group.selectionMode}`)}if(group.defaultEnabled!==undefined){rows.push(`defaultEnabled: ${group.defaultEnabled}`)}if(group.exclusiveGroup){rows.push(`exclusiveGroup: ${group.exclusiveGroup}`)}if(group.fallbackPriority!==undefined){rows.push(`fallbackPriority: ${group.fallbackPriority}`)}if(group.compatibleWith&&group.compatibleWith.length>0){rows.push(`compatibleWith: ${group.compatibleWith.join(", ")}`)}return rows}function dedupeGroupItems(items){const seen=new Set;const out=[];for(const item of items){const key=`${item.name}\x00${item.constraint??""}`;if(seen.has(key))continue;seen.add(key);out.push(item)}return out}function summariseGroupsByLifecycle(groups){const counts=new Map;for(const g of groups){counts.set(g.lifecycle,(counts.get(g.lifecycle)??0)+1)}const parts=[];for(const lc of["runtime","development","build","peer","optional"]){const n=counts.get(lc);if(n&&n>0)parts.push(`${n} ${lc}`)}return parts.join(", ")||"0"}function sortAlphabetically(items,key){return items.slice().sort((a,b)=>{const ka=key(a);const kb=key(b);return ka<kb?-1:ka>kb?1:0})}var schema5={target:z5.string().describe("Package registry:name[@version], for example npm:express@5.2.1; omit the version for latest. Go accepts versions with or without v; other registries reject v-prefixed git tags except Swift."),lifecycle:z5.union([z5.string(),z5.array(z5.string())]).optional().describe("Omit for runtime only. runtime, development, build, peer, optional (each adds that group to runtime), or all; one value, a comma list, or an array. all stands alone; case-insensitive."),include_importers:z5.boolean().optional().describe("Add importers (upstream package, its resolved version, declared constraint) to each transitive.packages[] entry. Default false; can quadruple large graphs. Requests the full transitive block unless max_depth bounds it."),include_issues:z5.boolean().optional().describe("Analyze deprecated, outdated, duplicate and conflicting packages. Default false; scans the full graph unless max_depth bounds it. JSON includes complete issue rows."),max_depth:z5.number().int().min(1).max(10).optional().describe("Add a `transitive` block and cap traversal at this depth (1-10). Omit for direct output unless `include_importers` is true; `include_issues` can still analyze the full graph."),format:z5.enum(["text","json"]).default("text").describe("Omit for text. Use json only when code consumes raw fields or text lacks a required field. JSON includes complete issue rows.")};var DESCRIPTION5="Inspect what a package depends on, directly or transitively. Lists direct runtime "+"dependencies with resolved versions; non-runtime groups are omitted by default. "+"Expand transitive footprint, provenance, or issue analysis only when needed, with "+"the corresponding fields; full-graph analysis is not local application lockfile "+"or reachability evidence. Supports "+`${SUPPORTED_DEPS_REGISTRIES_LIST}.`;function createPackageDependenciesTool(service){return{name:"pkg_deps",description:DESCRIPTION5,schema:schema5,annotations:OPEN_WORLD_READ_ONLY_TOOL_ANNOTATIONS,handler:async(args,context)=>{try{const target=parsePackageSpec(args.target.trim());const includeIssues=args.include_issues;const includeTransitiveOutput=args.max_depth!==undefined||args.include_importers===true;const wireMaxDepth=includeTransitiveOutput||includeIssues===true?args.max_depth:1;const{params,canonicalLifecycles}=buildPackageDependenciesParams({registry:target.registry,packageName:target.name,version:target.version,includeTransitive:true,maxDepth:wireMaxDepth,lifecycle:args.lifecycle,includeIssues});const showGroups=canonicalLifecycles.length>0&&!canonicalLifecycles.every((item)=>item==="runtime");const textFormat=isTextFormat3(args.format);const report=await service.packageDependencies({...params,includeTransitiveDetails:includeTransitiveOutput,includeGroups:showGroups||textFormat},...serviceRequestArgs(context?.signal));if(textFormat){const textLifecycles=canonicalLifecycles.length>0?canonicalLifecycles:["all"];return textResult(formatPackageDependenciesTerminal(report,{useColors:false,includeImporters:args.include_importers===true,requestedVersion:params.version,canonicalLifecycles:textLifecycles,includeTransitive:includeTransitiveOutput,maxDepth:args.max_depth,showGroups,hiddenGroupsHint:'pass lifecycle="all".',includeIssues,issuesDetailHint:'Pass format: "json" for complete issue details.'}).trimEnd())}const payload=buildPackageDependenciesSuccessPayload(report,{requestedVersion:params.version,canonicalLifecycles,includeTransitive:includeTransitiveOutput,maxDepth:args.max_depth,includeImporters:args.include_importers??false,includeIssues});return textResult(JSON.stringify(payload))}catch(error){throwIfCallerCancellation(error,context?.signal);const mapped=mapPackageIntelligenceError(error);return mcpMappedErrorResult(mapped,context,args.format,{recovery:{syntax:"mcp",tool:"pkg_deps",args}})}}}}function isTextFormat3(format){return format===undefined||format==="text"}import{z as z6}from"zod";function buildPackageSummaryParams(input){const trimmedName=input.packageName?.trim()??"";if(!trimmedName){throw new InvalidPackageSpecError("Package name is required.")}const registry=parsePkgseerRegistryArg(input.registry??"");if(!registry){throw new UnsupportedRegistryError(`Unsupported registry '${input.registry}'. Supported: ${PKGSEER_REGISTRY_LIST2}.`)}return{params:{registry:toPkgseerRegistry2(registry),packageName:trimmedName}}}function toIsoDate(iso){if(!iso)return null;const parsed=new Date(iso);if(Number.isNaN(parsed.getTime()))return null;return parsed.toISOString().slice(0,10)}var MINUTE=60;var HOUR=60*MINUTE;var DAY=24*HOUR;var MONTH=30*DAY;var YEAR=365*DAY;function toRelativeDate(iso,now=new Date){if(!iso)return null;const parsed=new Date(iso);if(Number.isNaN(parsed.getTime()))return null;const deltaSeconds=Math.floor((now.getTime()-parsed.getTime())/1000);if(deltaSeconds<0){return toIsoDate(iso)}if(deltaSeconds<MINUTE)return"just now";if(deltaSeconds<HOUR)return formatUnit(deltaSeconds,MINUTE,"minute");if(deltaSeconds<DAY)return formatUnit(deltaSeconds,HOUR,"hour");if(deltaSeconds<MONTH)return formatUnit(deltaSeconds,DAY,"day");if(deltaSeconds<YEAR)return formatUnit(deltaSeconds,MONTH,"month");return formatUnit(deltaSeconds,YEAR,"year")}function formatUnit(deltaSeconds,unit,label){const n=Math.floor(deltaSeconds/unit);return`${n} ${label}${n===1?"":"s"} ago`}function buildPackageSummarySuccessPayload(summary){const pkg=summary.package;const payload={registry:lowerRegistry2(pkg.registry),name:pkg.name,version:pkg.latestVersion};assignIfDefined(payload,"versionCount",pkg.versionCount);assignIfDefined(payload,"description",pkg.description);assignIfDefined(payload,"license",pkg.license);assignIfDefined(payload,"homepage",pkg.homepage);assignIfDefined(payload,"repository",pkg.repositoryUrl);assignIfDefined(payload,"registryRepository",pkg.registryRepository);assignIfDefined(payload,"publishedAt",toIsoDate(pkg.latestVersionPublishedAt));const downloads=buildDownloads(pkg.downloadsLastMonth,pkg.downloadsTotal,pkg.downloadsRefreshedAt);if(downloads)payload.downloads=downloads;const github=buildGithub(pkg.githubRepository);if(github)payload.github=github;const vulns=buildVulnerabilities(summary.security);if(vulns)payload.vulnerabilities=vulns;const advisoryHistory=buildAdvisoryHistory(summary.security);if(advisoryHistory)payload.advisoryHistory=advisoryHistory;const recent=buildRecentChanges(summary.latestChangelogs);if(recent)payload.recentChanges=recent;return payload}function lowerRegistry2(value){if(!value)return"";const upper=value.toUpperCase();try{return toPkgseerRegistryLowercase2(upper)}catch{return value.toLowerCase()}}function assignIfDefined(target,key,value){if(value!==undefined&&value!==null){target[key]=value}}function buildDownloads(lastMonth,total,refreshedAt){const result={};if(typeof lastMonth==="number")result.lastMonth=lastMonth;if(typeof total==="number")result.total=total;const normalizedRefresh=toIsoDate(refreshedAt);if(normalizedRefresh)result.refreshedAt=normalizedRefresh;return Object.keys(result).length>0?result:undefined}function buildGithub(github){if(!github)return;const result={};if(typeof github.stargazersCount==="number"){result.stars=github.stargazersCount}if(typeof github.forksCount==="number"){result.forks=github.forksCount}if(typeof github.openIssuesCount==="number"){result.openIssues=github.openIssuesCount}if(typeof github.archived==="boolean"){result.archived=github.archived}if(github.language){result.language=github.language}if(github.topics&&github.topics.length>0){result.topics=github.topics}const lastPushedAt=toIsoDate(github.pushedAt);if(lastPushedAt)result.lastPushedAt=lastPushedAt;return Object.keys(result).length>0?result:undefined}function buildVulnerabilities(security){if(!security)return;if(typeof security.vulnerabilityCount!=="number")return;const total=security.vulnerabilityCount;const result={total,affectsLatest:security.hasCurrentVulnerabilities??false};const recent=security.recentVulnerabilities?.map(buildVulnerability).filter((entry)=>entry!==undefined);if(recent&&recent.length>0){result.recent=recent}return result}function buildAdvisoryHistory(security){if(!security)return;return{total:security.allVulnerabilityCount}}function buildVulnerability(entry){const lean={};if(entry.osvId)lean.id=entry.osvId;if(entry.summary)lean.summary=entry.summary;if(typeof entry.severityScore==="number"&&entry.severityScore>0){lean.severity=entry.severityScore;lean.severityLabel=severityLabel(entry.severityScore)}const publishedAt=toIsoDate(entry.publishedAt);if(publishedAt)lean.publishedAt=publishedAt;return Object.keys(lean).length>0?lean:undefined}function severityLabel(score){if(score>=9)return"critical";if(score>=7)return"high";if(score>=4)return"medium";return"low"}function buildRecentChanges(entries){if(!entries||entries.length===0)return;const filtered=entries.filter((entry)=>!!entry.version).map((entry)=>{const lean={version:entry.version};const date=toIsoDate(entry.publishedAt);if(date)lean.date=date;const summary=pickChangelogSummary(entry);if(summary)lean.summary=summary;return lean});return filtered.length>0?filtered:undefined}function pickChangelogSummary(entry){if(!entry.body)return;const firstLine=entry.body.split(/\r?\n/).map((line)=>stripMarkdownHeading(line.trim())).find((line)=>line.length>0);if(!firstLine)return;return firstLine.length>120?`${firstLine.slice(0,117).trimEnd()}...`:firstLine}function stripMarkdownHeading(line){return line.replace(/^#{1,6}\s+/,"").trim()}function formatPackageSummaryTerminal(summary,options={}){const lean=buildPackageSummarySuccessPayload(summary);const useColors=options.useColors??false;const width=resolveWidth(options.terminalWidth);const now=options.now??new Date;const sections=[];const header=lean.license?`${colorize(lean.name,"bold",useColors)} @ ${lean.version} | ${lean.license}`:`${colorize(lean.name,"bold",useColors)} @ ${lean.version}`;sections.push(header);if(lean.description){sections.push(wrapText(lean.description,width))}const fields=buildFieldList(lean,summary,useColors,now,options.verbose??false,width);if(fields.length>0){sections.push(fields.join(`
|
|
97
|
+
`).trimEnd()}function formatGroupDependencyRow(dep,group,payload,nameWidth){const constraint=dep.constraint??"";if(group.lifecycle!=="runtime"){const name=dep.name.padEnd(nameWidth);return`${name} ${constraint}`.trimEnd()}const resolvedVersion=payload.runtime?.items.find((item)=>item.name===dep.name)?.version;if(!resolvedVersion){const name=dep.name.padEnd(nameWidth);return`${name} ${constraint}`.trimEnd()}const versionedName=`${dep.name}@${resolvedVersion}`.padEnd(nameWidth);return`${versionedName} ${constraint}`.trimEnd()}function formatEnvironmentMarker(marker){if(marker.type&&marker.value)return`${marker.type}: ${marker.value}`;if(marker.value)return marker.value;if(marker.type)return marker.type;return marker.raw??"(empty marker)"}function formatGroupHeading(group,registry){if(group.conditionType==="always"){return group.name}const displayCondition=displayConditionType(group.conditionType,registry);const showValue=group.conditionValue!==undefined&&group.conditionValue.toLowerCase()!==group.name.toLowerCase();const tail=showValue?`${displayCondition}: ${group.conditionValue}`:displayCondition;return`${group.name} (${group.lifecycle}, ${tail})`}function displayConditionType(conditionType,registry){if(conditionType==="feature"&®istry==="pypi")return"extra";return conditionType}function formatGroupMeta(group){const rows=[];if(group.selectionMode!=="required"){rows.push(`selectionMode: ${group.selectionMode}`)}if(group.defaultEnabled!==undefined){rows.push(`defaultEnabled: ${group.defaultEnabled}`)}if(group.exclusiveGroup){rows.push(`exclusiveGroup: ${group.exclusiveGroup}`)}if(group.fallbackPriority!==undefined){rows.push(`fallbackPriority: ${group.fallbackPriority}`)}if(group.compatibleWith&&group.compatibleWith.length>0){rows.push(`compatibleWith: ${group.compatibleWith.join(", ")}`)}return rows}function dedupeGroupItems(items){const seen=new Set;const out=[];for(const item of items){const key=`${item.name}\x00${item.constraint??""}`;if(seen.has(key))continue;seen.add(key);out.push(item)}return out}function summariseGroupsByLifecycle(groups){const counts=new Map;for(const g of groups){counts.set(g.lifecycle,(counts.get(g.lifecycle)??0)+1)}const parts=[];for(const lc of["runtime","development","build","peer","optional"]){const n=counts.get(lc);if(n&&n>0)parts.push(`${n} ${lc}`)}return parts.join(", ")||"0"}function sortAlphabetically(items,key){return items.slice().sort((a,b)=>{const ka=key(a);const kb=key(b);return ka<kb?-1:ka>kb?1:0})}var schema5={target:z5.string().describe("Package registry:name[@version], for example npm:express@5.2.1; omit the version for latest. Go accepts versions with or without v; other registries reject v-prefixed git tags except Swift."),lifecycle:z5.union([z5.string(),z5.array(z5.string())]).optional().describe("Omit for runtime only. runtime, development, build, peer, optional (each adds that group to runtime), or all; one value, a comma list, or an array. all stands alone; case-insensitive."),include_importers:z5.boolean().optional().describe("Add importers (upstream package, its resolved version, declared constraint) to each transitive.packages[] entry. Default false; can quadruple large graphs. Requests the full transitive block unless max_depth bounds it."),include_issues:z5.boolean().optional().describe("Analyze deprecated, outdated, duplicate and conflicting packages. Default false; scans the full graph unless max_depth bounds it. JSON includes complete issue rows."),max_depth:z5.number().int().min(1).max(10).optional().describe("Add a `transitive` block and cap traversal at this depth (1-10). Omit for direct output unless `include_importers` is true; `include_issues` can still analyze the full graph."),format:z5.enum(["text","json"]).default("text").describe("Omit for text. Use json only when code consumes raw fields or text lacks a required field. JSON includes complete issue rows.")};var DESCRIPTION5="Inspect what a package depends on, directly or transitively. Lists direct runtime "+"dependencies with resolved versions; non-runtime groups are omitted by default. "+"Expand transitive footprint, provenance, or issue analysis only when needed, with "+"the corresponding fields; full-graph analysis is not local application lockfile "+"or reachability evidence. Supports "+`${SUPPORTED_DEPS_REGISTRIES_LIST}.`;function createPackageDependenciesTool(service){return{name:"pkg_deps",description:DESCRIPTION5,schema:schema5,annotations:OPEN_WORLD_READ_ONLY_TOOL_ANNOTATIONS,handler:async(args,context)=>{try{const target=parsePackageSpec(args.target.trim());const includeIssues=args.include_issues;const includeTransitiveOutput=args.max_depth!==undefined||args.include_importers===true;const wireMaxDepth=includeTransitiveOutput||includeIssues===true?args.max_depth:1;const{params,canonicalLifecycles}=buildPackageDependenciesParams({registry:target.registry,packageName:target.name,version:target.version,includeTransitive:true,maxDepth:wireMaxDepth,lifecycle:args.lifecycle,includeIssues});const showGroups=canonicalLifecycles.length>0&&!canonicalLifecycles.every((item)=>item==="runtime");const textFormat=isTextFormat3(args.format);const report=await service.packageDependencies({...params,includeTransitiveDetails:includeTransitiveOutput,includeGroups:showGroups||textFormat},...serviceRequestArgs(context?.signal));if(textFormat){const textLifecycles=canonicalLifecycles.length>0?canonicalLifecycles:["all"];return textResult(formatPackageDependenciesTerminal(report,{useColors:false,includeImporters:args.include_importers===true,requestedVersion:params.version,canonicalLifecycles:textLifecycles,includeTransitive:includeTransitiveOutput,maxDepth:args.max_depth,showGroups,hiddenGroupsHint:'pass lifecycle="all".',includeIssues,issuesDetailHint:'Pass format: "json" for complete issue details.'}).trimEnd())}const payload=buildPackageDependenciesSuccessPayload(report,{requestedVersion:params.version,canonicalLifecycles,includeTransitive:includeTransitiveOutput,maxDepth:args.max_depth,includeImporters:args.include_importers??false,includeIssues});return textResult(JSON.stringify(payload))}catch(error){throwIfCallerCancellation(error,context?.signal);const mapped=mapPackageIntelligenceError(error);return mcpMappedErrorResult(mapped,context,args.format,{recovery:{syntax:"mcp",tool:"pkg_deps",args}})}}}}function isTextFormat3(format){return format===undefined||format==="text"}import{z as z6}from"zod";function buildPackageSummaryParams(input){const trimmedName=input.packageName?.trim()??"";if(!trimmedName){throw new InvalidPackageSpecError("Package name is required.")}const registry=parsePkgseerRegistryArg(input.registry??"");if(!registry){throw new UnsupportedRegistryError(`Unsupported registry '${input.registry}'. Supported: ${PKGSEER_REGISTRY_LIST2}.`)}return{params:{registry:toPkgseerRegistry2(registry),packageName:trimmedName}}}function toIsoDate(iso){if(!iso)return null;const parsed=new Date(iso);if(Number.isNaN(parsed.getTime()))return null;return parsed.toISOString().slice(0,10)}var MINUTE=60;var HOUR=60*MINUTE;var DAY=24*HOUR;var MONTH=30*DAY;var YEAR=365*DAY;function toRelativeDate(iso,now=new Date){if(!iso)return null;const parsed=new Date(iso);if(Number.isNaN(parsed.getTime()))return null;const deltaSeconds=Math.floor((now.getTime()-parsed.getTime())/1000);if(deltaSeconds<0){return toIsoDate(iso)}if(deltaSeconds<MINUTE)return"just now";if(deltaSeconds<HOUR)return formatUnit(deltaSeconds,MINUTE,"minute");if(deltaSeconds<DAY)return formatUnit(deltaSeconds,HOUR,"hour");if(deltaSeconds<MONTH)return formatUnit(deltaSeconds,DAY,"day");if(deltaSeconds<YEAR)return formatUnit(deltaSeconds,MONTH,"month");return formatUnit(deltaSeconds,YEAR,"year")}function formatUnit(deltaSeconds,unit,label){const n=Math.floor(deltaSeconds/unit);return`${n} ${label}${n===1?"":"s"} ago`}function buildPackageSummarySuccessPayload(summary){const pkg=summary.package;const payload={registry:lowerRegistry2(pkg.registry),name:pkg.name};assignIfDefined(payload,"version",pkg.version);assignIfDefined(payload,"latestVersion",pkg.latestVersion);assignIfDefined(payload,"latestVersionPublishedAt",toIsoDate(pkg.latestVersionPublishedAt));assignIfDefined(payload,"registryLatestDifference",pkg.registryLatestDifference);assignIfDefined(payload,"versionCount",pkg.versionCount);assignIfDefined(payload,"description",pkg.description);assignIfDefined(payload,"license",pkg.license);assignIfDefined(payload,"homepage",pkg.homepage);assignIfDefined(payload,"repository",pkg.repositoryUrl);assignIfDefined(payload,"registryRepository",pkg.registryRepository);assignIfDefined(payload,"publishedAt",toIsoDate(pkg.publishedAt));const downloads=buildDownloads(pkg.downloadsLastMonth,pkg.downloadsTotal,pkg.downloadsRefreshedAt);if(downloads)payload.downloads=downloads;const github=buildGithub(pkg.githubRepository);if(github)payload.github=github;const vulns=buildVulnerabilities(summary.security);if(vulns)payload.vulnerabilities=vulns;const advisoryHistory=buildAdvisoryHistory(summary.security);if(advisoryHistory)payload.advisoryHistory=advisoryHistory;const recent=buildRecentChanges(summary.latestChangelogs);if(recent)payload.recentChanges=recent;return payload}function lowerRegistry2(value){if(!value)return"";const upper=value.toUpperCase();try{return toPkgseerRegistryLowercase2(upper)}catch{return value.toLowerCase()}}function assignIfDefined(target,key,value){if(value!==undefined&&value!==null){target[key]=value}}function buildDownloads(lastMonth,total,refreshedAt){const result={};if(typeof lastMonth==="number")result.lastMonth=lastMonth;if(typeof total==="number")result.total=total;const normalizedRefresh=toIsoDate(refreshedAt);if(normalizedRefresh)result.refreshedAt=normalizedRefresh;return Object.keys(result).length>0?result:undefined}function buildGithub(github){if(!github)return;const result={};if(typeof github.stargazersCount==="number"){result.stars=github.stargazersCount}if(typeof github.forksCount==="number"){result.forks=github.forksCount}if(typeof github.openIssuesCount==="number"){result.openIssues=github.openIssuesCount}if(typeof github.archived==="boolean"){result.archived=github.archived}if(github.language){result.language=github.language}if(github.topics&&github.topics.length>0){result.topics=github.topics}const lastPushedAt=toIsoDate(github.pushedAt);if(lastPushedAt)result.lastPushedAt=lastPushedAt;return Object.keys(result).length>0?result:undefined}function buildVulnerabilities(security){if(!security)return;if(typeof security.vulnerabilityCount!=="number")return;const total=security.vulnerabilityCount;const result={total,affectsLatest:security.hasCurrentVulnerabilities??false};const recent=security.recentVulnerabilities?.map(buildVulnerability).filter((entry)=>entry!==undefined);if(recent&&recent.length>0){result.recent=recent}return result}function buildAdvisoryHistory(security){if(!security)return;return{total:security.allVulnerabilityCount}}function buildVulnerability(entry){const lean={};if(entry.osvId)lean.id=entry.osvId;if(entry.summary)lean.summary=entry.summary;if(typeof entry.severityScore==="number"&&entry.severityScore>0){lean.severity=entry.severityScore;lean.severityLabel=severityLabel(entry.severityScore)}const publishedAt=toIsoDate(entry.publishedAt);if(publishedAt)lean.publishedAt=publishedAt;return Object.keys(lean).length>0?lean:undefined}function severityLabel(score){if(score>=9)return"critical";if(score>=7)return"high";if(score>=4)return"medium";return"low"}function buildRecentChanges(entries){if(!entries||entries.length===0)return;const filtered=entries.filter((entry)=>!!entry.version).map((entry)=>{const lean={version:entry.version};const date=toIsoDate(entry.publishedAt);if(date)lean.date=date;const summary=pickChangelogSummary(entry);if(summary)lean.summary=summary;return lean});return filtered.length>0?filtered:undefined}function pickChangelogSummary(entry){if(!entry.body)return;const firstLine=entry.body.split(/\r?\n/).map((line)=>stripMarkdownHeading(line.trim())).find((line)=>line.length>0);if(!firstLine)return;return firstLine.length>120?`${firstLine.slice(0,117).trimEnd()}...`:firstLine}function stripMarkdownHeading(line){return line.replace(/^#{1,6}\s+/,"").trim()}function formatPackageSummaryTerminal(summary,options={}){const lean=buildPackageSummarySuccessPayload(summary);const useColors=options.useColors??false;const width=resolveWidth(options.terminalWidth);const now=options.now??new Date;const sections=[];const identity=lean.version?`${colorize(lean.name,"bold",useColors)} @ ${lean.version}`:`${colorize(lean.name,"bold",useColors)} (no selected version)`;sections.push(lean.license?`${identity} | ${lean.license}`:identity);const difference=formatRegistryLatestDifference(lean);if(difference)sections.push(wrapText(difference,width));if(lean.description){sections.push(wrapText(lean.description,width))}const fields=buildFieldList(lean,summary,useColors,now,options.verbose??false,width);if(fields.length>0){sections.push(fields.join(`
|
|
98
98
|
`))}if(options.verbose){const verbose=buildVerboseSections(lean,useColors);if(verbose.length>0)sections.push(verbose)}return`${sections.join(`
|
|
99
99
|
|
|
100
100
|
`)}
|
|
101
|
-
`}function resolveWidth(explicit){if(typeof explicit==="number"&&explicit>0){return Math.min(explicit,80)}const columns=process.stdout?.columns;if(typeof columns==="number"&&columns>0){return Math.min(columns,80)}return 80}function wrapText(text,width){const safeWidth=Math.max(1,width);const words=text.split(/\s+/);const lines=[];let current="";for(const word of words){if(word.length>safeWidth){if(current.length>0){lines.push(current);current=""}for(let offset=0;offset<word.length;offset+=safeWidth){const chunk=word.slice(offset,offset+safeWidth);if(chunk.length===safeWidth||offset+safeWidth<word.length){lines.push(chunk)}else{current=chunk}}continue}if(current.length===0){current=word;continue}if(current.length+1+word.length>safeWidth){lines.push(current);current=word}else{current+=` ${word}`}}if(current.length>0)lines.push(current);return lines.join(`
|
|
102
|
-
`)}function buildFieldList(lean,summary,useColors,now,verbose,width){const fields=[];if(lean.repository){const repositoryParts=[colorize(lean.repository,"cyan",useColors)];const githubPopularity=formatGithubPopularity(lean.github);if(githubPopularity)repositoryParts.push(`(${githubPopularity})`);fields.push({label:"Repository",value:repositoryParts.join(" ")})}else{const githubPopularity=formatGithubPopularity(lean.github);if(githubPopularity){fields.push({label:"GitHub",value:githubPopularity})}}if(lean.registryRepository){fields.push({label:"Package registry",value:`${lean.registryRepository.name} (${colorize(lean.registryRepository.url,"cyan",useColors)})`})}if(lean.homepage){fields.push({label:"Homepage",value:colorize(lean.homepage,"cyan",useColors)})}const publishedRelative=toRelativeDate(summary.package.
|
|
101
|
+
`}function formatRegistryLatestDifference(lean){const difference=lean.registryLatestDifference;if(!difference)return;const reasons={DEPRECATED:"is deprecated",YANKED:"is yanked",NO_FILES:"has no files",UNLISTED:"is unlisted",PRERELEASE_EXCLUDED:"is a prerelease"};const prefix=`latest ${difference.version} ${reasons[difference.reason]}`;if(difference.reason==="PRERELEASE_EXCLUDED"&&(!lean.version||lean.version===difference.version)){return`${prefix}; no default release; installing it requires an explicit version`}if(!lean.version||lean.version===difference.version)return`${prefix}; no default release`;const installHint=lean.registry==="npm"&&difference.reason==="DEPRECATED"?" (what npm installs)":"";return`${prefix}; showing ${lean.version}${installHint}`}function resolveWidth(explicit){if(typeof explicit==="number"&&explicit>0){return Math.min(explicit,80)}const columns=process.stdout?.columns;if(typeof columns==="number"&&columns>0){return Math.min(columns,80)}return 80}function wrapText(text,width){const safeWidth=Math.max(1,width);const words=text.split(/\s+/);const lines=[];let current="";for(const word of words){if(word.length>safeWidth){if(current.length>0){lines.push(current);current=""}for(let offset=0;offset<word.length;offset+=safeWidth){const chunk=word.slice(offset,offset+safeWidth);if(chunk.length===safeWidth||offset+safeWidth<word.length){lines.push(chunk)}else{current=chunk}}continue}if(current.length===0){current=word;continue}if(current.length+1+word.length>safeWidth){lines.push(current);current=word}else{current+=` ${word}`}}if(current.length>0)lines.push(current);return lines.join(`
|
|
102
|
+
`)}function buildFieldList(lean,summary,useColors,now,verbose,width){const fields=[];if(lean.repository){const repositoryParts=[colorize(lean.repository,"cyan",useColors)];const githubPopularity=formatGithubPopularity(lean.github);if(githubPopularity)repositoryParts.push(`(${githubPopularity})`);fields.push({label:"Repository",value:repositoryParts.join(" ")})}else{const githubPopularity=formatGithubPopularity(lean.github);if(githubPopularity){fields.push({label:"GitHub",value:githubPopularity})}}if(lean.registryRepository){fields.push({label:"Package registry",value:`${lean.registryRepository.name} (${colorize(lean.registryRepository.url,"cyan",useColors)})`})}if(lean.homepage){fields.push({label:"Homepage",value:colorize(lean.homepage,"cyan",useColors)})}const publishedRelative=toRelativeDate(summary.package.publishedAt,now);if(publishedRelative){fields.push({label:"Published",value:publishedRelative})}if(verbose&&lean.versionCount!==undefined){fields.push({label:"Versions",value:`${formatCompactNumber(lean.versionCount)} published`})}if(lean.downloads?.lastMonth!==undefined){const refreshed=verbose&&lean.downloads.refreshedAt?`; refreshed ${lean.downloads.refreshedAt}`:"";fields.push({label:"Downloads",value:`${formatCompactNumber(lean.downloads.lastMonth)} / month${refreshed}`})}else if(lean.downloads?.total!==undefined){const refreshed=verbose&&lean.downloads.refreshedAt?`; refreshed ${lean.downloads.refreshedAt}`:"";fields.push({label:"Downloads",value:`${formatCompactNumber(lean.downloads.total)} total${refreshed}`})}if(lean.advisoryHistory){fields.push({label:"Vulnerabilities",value:formatVulnerabilityStatus(lean.vulnerabilities,lean.advisoryHistory,lean.registryLatestDifference!==undefined)})}const labelWidth=Math.max(10,...fields.map((field)=>field.label.length));const valueIndent=" ".repeat(labelWidth+2);const valueWidth=Math.max(1,width-valueIndent.length);const lines=fields.flatMap((field)=>{const valueLines=field.label==="Vulnerabilities"?field.value.split(`
|
|
103
103
|
`).flatMap((value)=>wrapText(value,valueWidth).split(`
|
|
104
|
-
`)):[field.value];return valueLines.map((value,index)=>index===0?`${field.label.padEnd(labelWidth)} ${value}`:`${valueIndent}${value}`)});return lines}function formatGithubPopularity(github){if(!github)return;const parts=[];if(github.archived){parts.push("[ARCHIVED]")}if(github.stars!==undefined){parts.push(`${formatCompactNumber(github.stars)} stars`)}if(github.forks!==undefined){parts.push(`${formatCompactNumber(github.forks)} forks`)}if(github.openIssues!==undefined){parts.push(`${formatCompactNumber(github.openIssues)} issues`)}return parts.length>0?parts.join(", "):undefined}function formatVulnerabilityStatus(vulns,history){let latest;if(!vulns){latest
|
|
104
|
+
`)):[field.value];return valueLines.map((value,index)=>index===0?`${field.label.padEnd(labelWidth)} ${value}`:`${valueIndent}${value}`)});return lines}function formatGithubPopularity(github){if(!github)return;const parts=[];if(github.archived){parts.push("[ARCHIVED]")}if(github.stars!==undefined){parts.push(`${formatCompactNumber(github.stars)} stars`)}if(github.forks!==undefined){parts.push(`${formatCompactNumber(github.forks)} forks`)}if(github.openIssues!==undefined){parts.push(`${formatCompactNumber(github.openIssues)} issues`)}return parts.length>0?parts.join(", "):undefined}function formatVulnerabilityStatus(vulns,history,hasDifference){const label=hasDifference?"Selected":"Latest";let latest;if(!vulns){latest=`${label}: unavailable`}else if(vulns.total===0){latest=`${label}: none affected`}else{latest=`${label}: ${vulns.total} affected`}const historyNoun=history.total===1?"advisory":"advisories";const inconsistent=vulns!==undefined&&history.total<vulns.total;const historySuffix=inconsistent?" (inconsistent backend evidence)":"";const historyText=history.total===0?`History: none known across all versions${historySuffix}`:`History: ${history.total} known ${historyNoun} across all versions${historySuffix}`;return`${latest}
|
|
105
105
|
${historyText}`}function buildVerboseSections(lean,useColors){const blocks=[];if(lean.github){const github=formatVerboseGithub(lean.github,useColors);if(github)blocks.push(github)}if(lean.vulnerabilities?.recent&&lean.vulnerabilities.recent.length>0){blocks.push(formatVerboseAdvisories(lean.vulnerabilities.recent,useColors))}if(lean.recentChanges&&lean.recentChanges.length>0){blocks.push(formatVerboseChanges(lean.recentChanges,useColors))}return blocks.join(`
|
|
106
106
|
|
|
107
107
|
`)}function formatVerboseGithub(github,useColors){const fields=[];if(github.language)fields.push({label:"Language",value:github.language});if(github.lastPushedAt){fields.push({label:"Last pushed",value:github.lastPushedAt})}if(github.topics&&github.topics.length>0){fields.push({label:"Topics",value:github.topics.join(", ")})}const labelWidth=Math.max(10,...fields.map((field)=>field.label.length));return fields.length>0?[highlight("GitHub",useColors),...fields.map((field)=>` ${field.label.padEnd(labelWidth)} ${field.value}`)].join(`
|
|
108
108
|
`):undefined}function formatVerboseAdvisories(advisories,useColors){const labelWidth=Math.max(...advisories.map((a)=>(a.severityLabel??"").length));const lines=[highlight("Advisory history (all versions)",useColors)];for(const advisory of advisories){const parts=[];const label=(advisory.severityLabel??"").padEnd(labelWidth);if(label.trim().length>0)parts.push(label);if(advisory.id)parts.push(advisory.id);if(advisory.publishedAt)parts.push(advisory.publishedAt);if(advisory.summary)parts.push(advisory.summary);lines.push(` ${parts.join(" ")}`)}return lines.join(`
|
|
109
109
|
`)}function formatVerboseChanges(entries,useColors){const lines=[highlight("Recent changes",useColors)];for(const entry of entries){const parts=[entry.version];if(entry.date)parts.push(entry.date);if(entry.summary)parts.push(entry.summary);lines.push(` ${parts.join(" ")}`)}return lines.join(`
|
|
110
|
-
`)}var schema6={target:z6.string().describe(`
|
|
110
|
+
`)}var schema6={target:z6.string().describe(`Unversioned package registry:name, for example npm:express or npm:@types/node; omit version pins. Registries: ${PKGSEER_REGISTRY_LIST2}.`),verbose:z6.boolean().optional().describe("Text only. Adds GitHub language/topics/last-pushed, published-version count, download refresh date, package-wide advisory history (all versions), and recent changes. Selected-release affected and package-wide history counts are shown separately. Ignored for format=json."),format:z6.enum(["text","json"]).default("text").describe("Omit for text. Use json only when code consumes raw fields or text lacks a required field. JSON adds latestVersion, latestVersionPublishedAt, registryLatestDifference, versionCount, downloads.refreshedAt, advisoryHistory.total.")};var DESCRIPTION_BASE2="Assess package health and adoption: license, downloads, and activity. Provide "+"an unpinned package target; this tool describes the default selected release and explains a skipped registry latest. "+"Registry and source Git repository URLs, when reported, do not establish binary provenance or current availability. Default text returns these URLs, license, description, repository popularity "+"(stars/forks/issues and [ARCHIVED] when applicable), downloads, "+"publish age, selected-release affected count, and separate package-wide advisory "+"history count. Historical counts are not current-version risk. "+"Use `verbose: true` for additional health and history details. Use metadata directly; missing fields are unknown. The selected release and retrieval time do not prove registry freshness or historical release facts.";var DESCRIPTION6=`${DESCRIPTION_BASE2}
|
|
111
111
|
|
|
112
|
-
${PKG_INFO_GUARDRAIL}`;function createPackageSummaryTool(service){return{name:"pkg_info",description:DESCRIPTION6,schema:schema6,annotations:OPEN_WORLD_READ_ONLY_TOOL_ANNOTATIONS,handler:async(args,context)=>{try{const target=parsePackageSpec(args.target.trim());if(target.version!==undefined){throw new InvalidPackageSpecError(`pkg_info always returns the latest version; omit @${target.version}.`)}const{params}=buildPackageSummaryParams({registry:target.registry,packageName:target.name});const textFormat=isTextFormat4(args.format);const summary=await service.packageSummary({...params,includeVerboseFields:!textFormat||args.verbose===true},...serviceRequestArgs(context?.signal));const payload=buildPackageSummarySuccessPayload(summary);if(textFormat){return textResult(formatPackageSummaryTerminal(summary,{verbose:args.verbose,useColors:false}).trimEnd())}return textResult(JSON.stringify(payload))}catch(error){throwIfCallerCancellation(error,context?.signal);const mapped=mapPackageIntelligenceError(error);return mcpMappedErrorResult(mapped,context,args.format,{recovery:{syntax:"mcp",tool:"pkg_info",args}})}}}}function isTextFormat4(format){return format===undefined||format==="text"}import{z as z7}from"zod";class UnsupportedVulnerabilitiesRegistryError extends Error{constructor(message){super(message);this.name="UnsupportedVulnerabilitiesRegistryError"}}var SEVERITY_LABEL_TO_CVSS={low:0.1,medium:4,high:7,critical:9};var ADVISORY_SCOPE_TO_GRAPHQL={affected:"AFFECTED",non_affecting:"NON_AFFECTING",unknown:"UNKNOWN",all:"ALL"};function buildPackageVulnerabilitiesParams(input){const trimmedName=input.packageName?.trim()??"";if(!trimmedName){throw new InvalidPackageSpecError("Package name is required.")}const registryArg=parsePkgseerRegistryArg(input.registry??"");if(!registryArg){throw new UnsupportedRegistryError(`Unsupported registry '${input.registry}'. Supported: ${PKGSEER_REGISTRY_LIST2}.`)}const registry=toPkgseerRegistry2(registryArg);if(!supportsVulnerabilitiesRegistry(registry)){throw new UnsupportedVulnerabilitiesRegistryError(`pkg vulns only supports ${SUPPORTED_VULN_REGISTRIES_HUMAN}. Got: ${registryArg}.`)}const severityLabel=resolveMinSeverityLabel(input.minSeverity);const minSeverity=severityLabel!==undefined?SEVERITY_LABEL_TO_CVSS[severityLabel]:undefined;const version=normalisePackageVersion(input.version,registry,{rejectLeadingV:true});const advisoryScope=resolveAdvisoryScope(input.advisoryScope);const filterWithScope=buildFilterEcho(severityLabel,input.includeWithdrawn,advisoryScope);return{params:{registry,packageName:trimmedName,version,minSeverity,includeWithdrawn:input.includeWithdrawn,includeTransitive:input.includeTransitive,advisoryScope:advisoryScope?ADVISORY_SCOPE_TO_GRAPHQL[advisoryScope]:undefined},...filterWithScope?{filter:filterWithScope}:{}}}function resolveMinSeverityLabel(raw){if(raw===undefined)return;const trimmed=raw.trim();if(trimmed.length===0)return;const lower=trimmed.toLowerCase();if(!isSeverityLabel(lower)){throw new InvalidPackageSpecError(`Unsupported severity '${raw}'. Expected one of: low, medium, high, critical.`)}return lower}function buildFilterEcho(minSeverity,includeWithdrawn,advisoryScope){const filter={};if(minSeverity!==undefined)filter.minSeverity=minSeverity;if(includeWithdrawn===true)filter.includeWithdrawn=true;if(advisoryScope!==undefined&&advisoryScope!=="affected"){filter.advisoryScope=advisoryScope}return Object.keys(filter).length>0?filter:undefined}function resolveAdvisoryScope(raw){if(raw===undefined)return;const trimmed=raw.trim();if(trimmed.length===0)return;const lower=trimmed.toLowerCase().replace(/-/g,"_");if(lower==="affected"||lower==="non_affecting"||lower==="unknown"||lower==="all"){return lower}throw new InvalidPackageSpecError(`Unsupported advisory scope '${raw}'. Expected one of: affected, non_affecting, unknown, all.`)}function isSeverityLabel(value){return value==="low"||value==="medium"||value==="high"||value==="critical"}var DEFAULT_CHANGELOG_LIMIT=20;var PACKAGE_UPGRADE_REVIEW_MAX_PACKAGES=30;function buildPackageUpgradeReviewRequest(input){const batch=input.packages?.filter((pkg)=>!isBlankPackageInput(pkg));const hasBatch=Array.isArray(batch)&&batch.length>0;const hasSingle=hasNonBlankValue(input.registry)||hasNonBlankValue(input.packageName)||hasNonBlankValue(input.currentVersion)||hasNonBlankValue(input.targetVersion);if(hasBatch&&hasSingle){throw new InvalidPackageSpecError("Pass either packages[] or registry/package_name/current_version/target_version, not both.")}if(!hasBatch&&!hasSingle){throw new InvalidPackageSpecError("Package upgrade review requires either packages[] or registry, package_name, current_version, and target_version.")}const packages=hasBatch?parseBatch(batch):[parsePackageInput({registry:input.registry??"",packageName:input.packageName??"",currentVersion:input.currentVersion??"",targetVersion:input.targetVersion??""})];const minSeverityLabel=resolveMinSeverityLabel2(input.minSeverity);const hasExplicitChanges=Boolean(input.changes?.trim());const explicitChanges=hasExplicitChanges?normaliseChangelogChanges(input.changes):undefined;const changesSelection=explicitChanges??"focused";const statementTiers=changesSelection==="focused"?["MUST_ACT","SHOULD_KNOW","UNCLASSIFIED"]:changesSelection==="actionable"?["MUST_ACT"]:changesSelection==="important"?["MUST_ACT","SHOULD_KNOW"]:undefined;const changelogView=input.format==="json"?"json":packages.length>1&&input.verbose!==true?"triage":"text";return{packages,options:{changelogView,changesSelection,explicitChanges,statementTiers,includeTransitiveSecurity:input.includeTransitiveSecurity!==false,includeDependencyIssues:input.includeDependencyIssues===true,includeDependencyChanges:true,changelogLimit:DEFAULT_CHANGELOG_LIMIT,minSeverityLabel,minSeverity:minSeverityLabel!==undefined&&minSeverityLabel!=="low"?SEVERITY_LABEL_TO_CVSS[minSeverityLabel]:undefined}}}function hasNonBlankValue(value){return value!==undefined&&value.trim().length>0}function isBlankPackageInput(input){return!(hasNonBlankValue(input.registry)||hasNonBlankValue(input.packageName)||hasNonBlankValue(input.currentVersion)||hasNonBlankValue(input.targetVersion))}function parseBatch(packages){if(!Array.isArray(packages)||packages.length===0){throw new InvalidPackageSpecError("packages[] must contain at least one upgrade.")}if(packages.length>PACKAGE_UPGRADE_REVIEW_MAX_PACKAGES){throw new InvalidPackageSpecError(`packages[] must contain at most ${PACKAGE_UPGRADE_REVIEW_MAX_PACKAGES} upgrades.`)}return packages.map(parsePackageInput)}function parsePackageInput(input){const registryArg=parsePkgseerRegistryArg(input.registry??"");if(!registryArg){throw new UnsupportedRegistryError(`Unsupported registry '${input.registry}'. Supported: ${PKGSEER_REGISTRY_LIST2}.`)}const packageName=input.packageName?.trim()??"";if(packageName.length===0){throw new InvalidPackageSpecError("Package name is required.")}const registry=toPkgseerRegistry2(registryArg);const currentVersion=normaliseVersion(input.currentVersion,"current_version",registry);const targetVersion=normaliseVersion(input.targetVersion,"target_version",registry);return{registry,registryLabel:registryArg,packageName,currentVersion,targetVersion}}function normaliseVersion(raw,fieldName,registry){const version=normalisePackageVersion(raw,registry,{rejectLeadingV:true,fieldName});if(version===undefined){throw new InvalidPackageSpecError(`${fieldName} is required.`)}return version}function resolveMinSeverityLabel2(raw){if(raw===undefined)return;const lower=raw.trim().toLowerCase();if(lower.length===0)return;if(lower==="low"||lower==="medium"||lower==="high"||lower==="critical"){return lower}throw new InvalidPackageSpecError(`Unsupported min_severity '${raw}'. Expected one of: low, medium, high, critical.`)}function formatVulnerabilityAssessmentReason(reason){switch(reason){case"LOOKUP_FAILED":return"Advisory lookup failed";case"INVALID_VERSION":return"Version could not be evaluated";case"INVALID_RANGE":return"Advisory range could not be evaluated";case"MISSING_RANGES":return"Advisory has no affected ranges";default:return reason}}function formatAdvisoryAssessment(status,affected){if(status==="AFFECTED")return"affects this version";if(status==="NON_AFFECTING")return"non-affecting";if(status==="UNKNOWN")return"unknown";if(status!==undefined)return status;if(affected===true)return"affects this version";if(affected===false)return"non-affecting";return}function isAssessmentStatusImplied(status,affected){return status===undefined||status==="AFFECTED"&&affected===true||status==="NON_AFFECTING"&&affected===false}function formatAssessmentUncertainty(status,affected){if(isAssessmentStatusImplied(status,affected))return;switch(status){case"UNSUPPORTED":return"no vulnerability data for this registry; no findings is not evidence of safety";case"UNKNOWN":return"assessment incomplete";case"NOT_ASSESSED":return"no concrete version assessed";default:return status}}async function buildPackageUpgradeReview(service,packages,options,signal){const response=await service.packageUpgradeReview({packages:packages.map((pkg)=>({registry:pkg.registry,name:pkg.packageName,currentVersion:pkg.currentVersion,targetVersion:pkg.targetVersion})),changelogView:options.changelogView,statementTiers:options.statementTiers,includeTransitiveSecurity:options.includeTransitiveSecurity,includeDependencyIssues:options.includeDependencyIssues,changelogLimit:options.changelogLimit,minSeverity:options.minSeverity},...serviceRequestArgs(signal));const result=normaliseBackendUpgradeReviewResponse(response,options.changesSelection);if(options.explicitChanges)result.filter={changes:options.explicitChanges};return result}function normaliseBackendUpgradeReviewResponse(response,selection){return{summary:response.summary,reviews:response.reviews.map((review)=>({registry:lowerEnum(review.registry)??review.registry,name:review.name,currentVersion:review.currentVersion,targetVersion:review.targetVersion,latestVersion:review.latestVersion,versionDelta:lowerEnum(review.versionDelta),migrationGuides:review.migrationGuides,security:normaliseBackendSecurity(review.security),changelog:normaliseBackendChangelog(review.changelog,selection),compatibility:review.compatibility,dependencyChanges:review.dependencyChanges?normaliseBackendDependencyChanges(review.dependencyChanges):undefined,dependencyIssues:review.dependencyIssues,unknowns:review.unknowns,unknownDetails:review.unknownDetails}))}}function normaliseBackendSecurity(security){return{current:security.current?normaliseBackendVersionVulnerabilitySummary(security.current):undefined,target:security.target?normaliseBackendVersionVulnerabilitySummary(security.target):undefined,added:security.added.map(normaliseBackendAdvisory),removed:security.removed.map(normaliseBackendAdvisory),notAddressed:security.notAddressed.map(normaliseBackendAdvisory),fixed:security.fixed.map(normaliseBackendAdvisory),introduced:security.introduced.map(normaliseBackendAdvisory),unchanged:security.unchanged.map(normaliseBackendAdvisory),transitive:security.transitive?normaliseBackendTransitiveSecurity(security.transitive):undefined}}function normaliseBackendVersionVulnerabilitySummary(summary){return{version:summary.version,publishedAt:summary.publishedAt,deprecated:summary.deprecated,deprecationReason:summary.deprecationReason,affectedCount:summary.affectedCount,unknownVulnerabilityCount:summary.unknownVulnerabilityCount,assessmentStatus:summary.assessmentStatus,nonAffectingCount:summary.nonAffectingCount,allCount:summary.allCount,advisories:summary.advisories.map(normaliseBackendAdvisory)}}function normaliseBackendAdvisory(advisory){return{assessmentStatus:isAssessmentStatusImplied(advisory.assessmentStatus,true)?undefined:advisory.assessmentStatus,assessmentReasons:advisory.assessmentReasons?.length?advisory.assessmentReasons:undefined,id:advisory.id,aliases:advisory.aliases,summary:advisory.summary,severity:advisory.severity,severityLabel:lowerEnum(advisory.severityLabel),fixedIn:advisory.fixedIn,isMalicious:advisory.isMalicious}}function normaliseBackendTransitiveSecurity(transitive){return{currentAffected:transitive.currentAffected,targetAffected:transitive.targetAffected,introducedPackages:transitive.introducedPackages.map(normaliseRegistryPrefix),fixedPackages:transitive.fixedPackages.map(normaliseRegistryPrefix),introducedPackageDetails:transitive.introducedPackageDetails.entries.map(normaliseBackendTransitivePackage),introducedPackageDetailsTotalCount:transitive.introducedPackageDetails.totalCount,introducedPackageDetailsTruncated:transitive.introducedPackageDetails.truncated,fixedPackageDetails:transitive.fixedPackageDetails.entries.map(normaliseBackendTransitivePackage),fixedPackageDetailsTotalCount:transitive.fixedPackageDetails.totalCount,fixedPackageDetailsTruncated:transitive.fixedPackageDetails.truncated,stillAffectedPackageDetails:transitive.stillAffectedPackageDetails.entries.map(normaliseBackendTransitivePackage),stillAffectedPackageDetailsTotalCount:transitive.stillAffectedPackageDetails.totalCount,stillAffectedPackageDetailsTruncated:transitive.stillAffectedPackageDetails.truncated}}function normaliseBackendDependencyChanges(changes){return{direct:normaliseBackendDependencyChangeGroup(changes.direct),transitive:normaliseBackendDependencyChangeGroup(changes.transitive)}}function normaliseBackendDependencyChangeGroup(group){return{added:group.added.map(normaliseBackendDependencyChangeItem),removed:group.removed.map(normaliseBackendDependencyChangeItem),changed:group.changed.map(normaliseBackendDependencyChangeItem)}}function normaliseBackendDependencyChangeItem(item){return{name:item.name,registry:lowerEnum(item.registry),version:item.version,fromVersions:item.fromVersions,toVersions:item.toVersions,constraint:item.constraint,type:lowerEnum(item.type)}}function normaliseBackendTransitivePackage(pkg){return{id:pkg.id,registry:lowerEnum(pkg.registry)??pkg.registry,name:pkg.name,versions:pkg.versions,affectedCount:pkg.affectedCount,maxSeverityScore:pkg.maxSeverityScore,maxSeverityLabel:lowerEnum(pkg.maxSeverityLabel),advisoryIds:pkg.advisoryIds}}function normaliseBackendChangelog(changelog,selection){return{...changelog.statements?{statements:{...normaliseChangelogStatements(changelog.statements),selection}}:{},riskCoverage:{...changelog.riskCoverage},source:lowerEnum(changelog.source),fallback:lowerEnum(changelog.fallback),entries:changelog.entries?.map(normaliseBackendChangelogEntry),sampledEntries:changelog.sampledEntries?.map(normaliseBackendChangelogEntry),keywordEntries:changelog.keywordEntries?.map(normaliseBackendChangelogEntry),totalKeywordEntries:changelog.totalKeywordEntries,totalEntries:changelog.totalEntries,totalEntriesWithBodies:changelog.totalEntriesWithBodies,truncated:changelog.truncated,hasReleaseNoteBodies:changelog.hasReleaseNoteBodies,breakingSignals:changelog.breakingSignals,migrationSignals:changelog.migrationSignals}}function normaliseBackendChangelogEntry(entry){return{detailSource:lowerEnum(entry.detailSource),version:entry.version??null,publishedAt:entry.publishedAt,htmlUrl:entry.htmlUrl,body:entry.body,bodyPreview:entry.bodyPreview,headline:entry.headline,signals:entry.signals.length>0?entry.signals:undefined}}function lowerEnum(value){return value?.toLowerCase()}function normaliseRegistryPrefix(value){return value.replace(/^([A-Z_]+):/,(prefix)=>prefix.toLowerCase())}function changelogSignalText(body){if(!body)return"";const lines=body.replace(/\r\n/g,`
|
|
112
|
+
${PKG_INFO_GUARDRAIL}`;function createPackageSummaryTool(service){return{name:"pkg_info",description:DESCRIPTION6,schema:schema6,annotations:OPEN_WORLD_READ_ONLY_TOOL_ANNOTATIONS,handler:async(args,context)=>{try{const target=parsePackageSpec(args.target.trim());if(target.version!==undefined){throw new InvalidPackageSpecError(`pkg_info returns the default selected release; omit @${target.version}.`)}const{params}=buildPackageSummaryParams({registry:target.registry,packageName:target.name});const textFormat=isTextFormat4(args.format);const summary=await service.packageSummary({...params,includeVerboseFields:!textFormat||args.verbose===true},...serviceRequestArgs(context?.signal));const payload=buildPackageSummarySuccessPayload(summary);if(textFormat){return textResult(formatPackageSummaryTerminal(summary,{verbose:args.verbose,useColors:false}).trimEnd())}return textResult(JSON.stringify(payload))}catch(error){throwIfCallerCancellation(error,context?.signal);const mapped=mapPackageIntelligenceError(error);return mcpMappedErrorResult(mapped,context,args.format,{recovery:{syntax:"mcp",tool:"pkg_info",args}})}}}}function isTextFormat4(format){return format===undefined||format==="text"}import{z as z7}from"zod";class UnsupportedVulnerabilitiesRegistryError extends Error{constructor(message){super(message);this.name="UnsupportedVulnerabilitiesRegistryError"}}var SEVERITY_LABEL_TO_CVSS={low:0.1,medium:4,high:7,critical:9};var ADVISORY_SCOPE_TO_GRAPHQL={affected:"AFFECTED",non_affecting:"NON_AFFECTING",unknown:"UNKNOWN",all:"ALL"};function buildPackageVulnerabilitiesParams(input){const trimmedName=input.packageName?.trim()??"";if(!trimmedName){throw new InvalidPackageSpecError("Package name is required.")}const registryArg=parsePkgseerRegistryArg(input.registry??"");if(!registryArg){throw new UnsupportedRegistryError(`Unsupported registry '${input.registry}'. Supported: ${PKGSEER_REGISTRY_LIST2}.`)}const registry=toPkgseerRegistry2(registryArg);if(!supportsVulnerabilitiesRegistry(registry)){throw new UnsupportedVulnerabilitiesRegistryError(`pkg vulns only supports ${SUPPORTED_VULN_REGISTRIES_HUMAN}. Got: ${registryArg}.`)}const severityLabel=resolveMinSeverityLabel(input.minSeverity);const minSeverity=severityLabel!==undefined?SEVERITY_LABEL_TO_CVSS[severityLabel]:undefined;const version=normalisePackageVersion(input.version,registry,{rejectLeadingV:true});const advisoryScope=resolveAdvisoryScope(input.advisoryScope);const filterWithScope=buildFilterEcho(severityLabel,input.includeWithdrawn,advisoryScope);return{params:{registry,packageName:trimmedName,version,minSeverity,includeWithdrawn:input.includeWithdrawn,includeTransitive:input.includeTransitive,advisoryScope:advisoryScope?ADVISORY_SCOPE_TO_GRAPHQL[advisoryScope]:undefined},...filterWithScope?{filter:filterWithScope}:{}}}function resolveMinSeverityLabel(raw){if(raw===undefined)return;const trimmed=raw.trim();if(trimmed.length===0)return;const lower=trimmed.toLowerCase();if(!isSeverityLabel(lower)){throw new InvalidPackageSpecError(`Unsupported severity '${raw}'. Expected one of: low, medium, high, critical.`)}return lower}function buildFilterEcho(minSeverity,includeWithdrawn,advisoryScope){const filter={};if(minSeverity!==undefined)filter.minSeverity=minSeverity;if(includeWithdrawn===true)filter.includeWithdrawn=true;if(advisoryScope!==undefined&&advisoryScope!=="affected"){filter.advisoryScope=advisoryScope}return Object.keys(filter).length>0?filter:undefined}function resolveAdvisoryScope(raw){if(raw===undefined)return;const trimmed=raw.trim();if(trimmed.length===0)return;const lower=trimmed.toLowerCase().replace(/-/g,"_");if(lower==="affected"||lower==="non_affecting"||lower==="unknown"||lower==="all"){return lower}throw new InvalidPackageSpecError(`Unsupported advisory scope '${raw}'. Expected one of: affected, non_affecting, unknown, all.`)}function isSeverityLabel(value){return value==="low"||value==="medium"||value==="high"||value==="critical"}var DEFAULT_CHANGELOG_LIMIT=20;var PACKAGE_UPGRADE_REVIEW_MAX_PACKAGES=30;function buildPackageUpgradeReviewRequest(input){const batch=input.packages?.filter((pkg)=>!isBlankPackageInput(pkg));const hasBatch=Array.isArray(batch)&&batch.length>0;const hasSingle=hasNonBlankValue(input.registry)||hasNonBlankValue(input.packageName)||hasNonBlankValue(input.currentVersion)||hasNonBlankValue(input.targetVersion);if(hasBatch&&hasSingle){throw new InvalidPackageSpecError("Pass either packages[] or registry/package_name/current_version/target_version, not both.")}if(!hasBatch&&!hasSingle){throw new InvalidPackageSpecError("Package upgrade review requires either packages[] or registry, package_name, current_version, and target_version.")}const packages=hasBatch?parseBatch(batch):[parsePackageInput({registry:input.registry??"",packageName:input.packageName??"",currentVersion:input.currentVersion??"",targetVersion:input.targetVersion??""})];const minSeverityLabel=resolveMinSeverityLabel2(input.minSeverity);const hasExplicitChanges=Boolean(input.changes?.trim());const explicitChanges=hasExplicitChanges?normaliseChangelogChanges(input.changes):undefined;const changesSelection=explicitChanges??"focused";const statementTiers=changesSelection==="focused"?["MUST_ACT","SHOULD_KNOW","UNCLASSIFIED"]:changesSelection==="actionable"?["MUST_ACT"]:changesSelection==="important"?["MUST_ACT","SHOULD_KNOW"]:undefined;const changelogView=input.format==="json"?"json":packages.length>1&&input.verbose!==true?"triage":"text";return{packages,options:{changelogView,changesSelection,explicitChanges,statementTiers,includeTransitiveSecurity:input.includeTransitiveSecurity!==false,includeDependencyIssues:input.includeDependencyIssues===true,includeDependencyChanges:true,changelogLimit:DEFAULT_CHANGELOG_LIMIT,minSeverityLabel,minSeverity:minSeverityLabel!==undefined&&minSeverityLabel!=="low"?SEVERITY_LABEL_TO_CVSS[minSeverityLabel]:undefined}}}function hasNonBlankValue(value){return value!==undefined&&value.trim().length>0}function isBlankPackageInput(input){return!(hasNonBlankValue(input.registry)||hasNonBlankValue(input.packageName)||hasNonBlankValue(input.currentVersion)||hasNonBlankValue(input.targetVersion))}function parseBatch(packages){if(!Array.isArray(packages)||packages.length===0){throw new InvalidPackageSpecError("packages[] must contain at least one upgrade.")}if(packages.length>PACKAGE_UPGRADE_REVIEW_MAX_PACKAGES){throw new InvalidPackageSpecError(`packages[] must contain at most ${PACKAGE_UPGRADE_REVIEW_MAX_PACKAGES} upgrades.`)}return packages.map(parsePackageInput)}function parsePackageInput(input){const registryArg=parsePkgseerRegistryArg(input.registry??"");if(!registryArg){throw new UnsupportedRegistryError(`Unsupported registry '${input.registry}'. Supported: ${PKGSEER_REGISTRY_LIST2}.`)}const packageName=input.packageName?.trim()??"";if(packageName.length===0){throw new InvalidPackageSpecError("Package name is required.")}const registry=toPkgseerRegistry2(registryArg);const currentVersion=normaliseVersion(input.currentVersion,"current_version",registry);const targetVersion=normaliseVersion(input.targetVersion,"target_version",registry);return{registry,registryLabel:registryArg,packageName,currentVersion,targetVersion}}function normaliseVersion(raw,fieldName,registry){const version=normalisePackageVersion(raw,registry,{rejectLeadingV:true,fieldName});if(version===undefined){throw new InvalidPackageSpecError(`${fieldName} is required.`)}return version}function resolveMinSeverityLabel2(raw){if(raw===undefined)return;const lower=raw.trim().toLowerCase();if(lower.length===0)return;if(lower==="low"||lower==="medium"||lower==="high"||lower==="critical"){return lower}throw new InvalidPackageSpecError(`Unsupported min_severity '${raw}'. Expected one of: low, medium, high, critical.`)}function formatVulnerabilityAssessmentReason(reason){switch(reason){case"LOOKUP_FAILED":return"Advisory lookup failed";case"INVALID_VERSION":return"Version could not be evaluated";case"INVALID_RANGE":return"Advisory range could not be evaluated";case"MISSING_RANGES":return"Advisory has no affected ranges";default:return reason}}function formatAdvisoryAssessment(status,affected){if(status==="AFFECTED")return"affects this version";if(status==="NON_AFFECTING")return"non-affecting";if(status==="UNKNOWN")return"unknown";if(status!==undefined)return status;if(affected===true)return"affects this version";if(affected===false)return"non-affecting";return}function isAssessmentStatusImplied(status,affected){return status===undefined||status==="AFFECTED"&&affected===true||status==="NON_AFFECTING"&&affected===false}function formatAssessmentUncertainty(status,affected){if(isAssessmentStatusImplied(status,affected))return;switch(status){case"UNSUPPORTED":return"no vulnerability data for this registry; no findings is not evidence of safety";case"UNKNOWN":return"assessment incomplete";case"NOT_ASSESSED":return"no concrete version assessed";default:return status}}async function buildPackageUpgradeReview(service,packages,options,signal){const response=await service.packageUpgradeReview({packages:packages.map((pkg)=>({registry:pkg.registry,name:pkg.packageName,currentVersion:pkg.currentVersion,targetVersion:pkg.targetVersion})),changelogView:options.changelogView,statementTiers:options.statementTiers,includeTransitiveSecurity:options.includeTransitiveSecurity,includeDependencyIssues:options.includeDependencyIssues,changelogLimit:options.changelogLimit,minSeverity:options.minSeverity},...serviceRequestArgs(signal));const result=normaliseBackendUpgradeReviewResponse(response,options.changesSelection);if(options.explicitChanges)result.filter={changes:options.explicitChanges};return result}function normaliseBackendUpgradeReviewResponse(response,selection){return{summary:response.summary,reviews:response.reviews.map((review)=>({registry:lowerEnum(review.registry)??review.registry,name:review.name,currentVersion:review.currentVersion,targetVersion:review.targetVersion,latestVersion:review.latestVersion,versionDelta:lowerEnum(review.versionDelta),migrationGuides:review.migrationGuides,security:normaliseBackendSecurity(review.security),changelog:normaliseBackendChangelog(review.changelog,selection),compatibility:review.compatibility,dependencyChanges:review.dependencyChanges?normaliseBackendDependencyChanges(review.dependencyChanges):undefined,dependencyIssues:review.dependencyIssues,unknowns:review.unknowns,unknownDetails:review.unknownDetails}))}}function normaliseBackendSecurity(security){return{current:security.current?normaliseBackendVersionVulnerabilitySummary(security.current):undefined,target:security.target?normaliseBackendVersionVulnerabilitySummary(security.target):undefined,added:security.added.map(normaliseBackendAdvisory),removed:security.removed.map(normaliseBackendAdvisory),notAddressed:security.notAddressed.map(normaliseBackendAdvisory),fixed:security.fixed.map(normaliseBackendAdvisory),introduced:security.introduced.map(normaliseBackendAdvisory),unchanged:security.unchanged.map(normaliseBackendAdvisory),transitive:security.transitive?normaliseBackendTransitiveSecurity(security.transitive):undefined}}function normaliseBackendVersionVulnerabilitySummary(summary){return{version:summary.version,publishedAt:summary.publishedAt,deprecated:summary.deprecated,deprecationReason:summary.deprecationReason,affectedCount:summary.affectedCount,unknownVulnerabilityCount:summary.unknownVulnerabilityCount,assessmentStatus:summary.assessmentStatus,nonAffectingCount:summary.nonAffectingCount,allCount:summary.allCount,advisories:summary.advisories.map(normaliseBackendAdvisory)}}function normaliseBackendAdvisory(advisory){return{assessmentStatus:isAssessmentStatusImplied(advisory.assessmentStatus,true)?undefined:advisory.assessmentStatus,assessmentReasons:advisory.assessmentReasons?.length?advisory.assessmentReasons:undefined,id:advisory.id,aliases:advisory.aliases,summary:advisory.summary,severity:advisory.severity,severityLabel:lowerEnum(advisory.severityLabel),fixedIn:advisory.fixedIn,isMalicious:advisory.isMalicious}}function normaliseBackendTransitiveSecurity(transitive){return{currentAffected:transitive.currentAffected,targetAffected:transitive.targetAffected,introducedPackages:transitive.introducedPackages.map(normaliseRegistryPrefix),fixedPackages:transitive.fixedPackages.map(normaliseRegistryPrefix),introducedPackageDetails:transitive.introducedPackageDetails.entries.map(normaliseBackendTransitivePackage),introducedPackageDetailsTotalCount:transitive.introducedPackageDetails.totalCount,introducedPackageDetailsTruncated:transitive.introducedPackageDetails.truncated,fixedPackageDetails:transitive.fixedPackageDetails.entries.map(normaliseBackendTransitivePackage),fixedPackageDetailsTotalCount:transitive.fixedPackageDetails.totalCount,fixedPackageDetailsTruncated:transitive.fixedPackageDetails.truncated,stillAffectedPackageDetails:transitive.stillAffectedPackageDetails.entries.map(normaliseBackendTransitivePackage),stillAffectedPackageDetailsTotalCount:transitive.stillAffectedPackageDetails.totalCount,stillAffectedPackageDetailsTruncated:transitive.stillAffectedPackageDetails.truncated}}function normaliseBackendDependencyChanges(changes){return{direct:normaliseBackendDependencyChangeGroup(changes.direct),transitive:normaliseBackendDependencyChangeGroup(changes.transitive)}}function normaliseBackendDependencyChangeGroup(group){return{added:group.added.map(normaliseBackendDependencyChangeItem),removed:group.removed.map(normaliseBackendDependencyChangeItem),changed:group.changed.map(normaliseBackendDependencyChangeItem)}}function normaliseBackendDependencyChangeItem(item){return{name:item.name,registry:lowerEnum(item.registry),version:item.version,fromVersions:item.fromVersions,toVersions:item.toVersions,constraint:item.constraint,type:lowerEnum(item.type)}}function normaliseBackendTransitivePackage(pkg){return{id:pkg.id,registry:lowerEnum(pkg.registry)??pkg.registry,name:pkg.name,versions:pkg.versions,affectedCount:pkg.affectedCount,maxSeverityScore:pkg.maxSeverityScore,maxSeverityLabel:lowerEnum(pkg.maxSeverityLabel),advisoryIds:pkg.advisoryIds}}function normaliseBackendChangelog(changelog,selection){return{...changelog.statements?{statements:{...normaliseChangelogStatements(changelog.statements),selection}}:{},riskCoverage:{...changelog.riskCoverage},source:lowerEnum(changelog.source),fallback:lowerEnum(changelog.fallback),entries:changelog.entries?.map(normaliseBackendChangelogEntry),sampledEntries:changelog.sampledEntries?.map(normaliseBackendChangelogEntry),keywordEntries:changelog.keywordEntries?.map(normaliseBackendChangelogEntry),totalKeywordEntries:changelog.totalKeywordEntries,totalEntries:changelog.totalEntries,totalEntriesWithBodies:changelog.totalEntriesWithBodies,truncated:changelog.truncated,hasReleaseNoteBodies:changelog.hasReleaseNoteBodies,breakingSignals:changelog.breakingSignals,migrationSignals:changelog.migrationSignals}}function normaliseBackendChangelogEntry(entry){return{detailSource:lowerEnum(entry.detailSource),version:entry.version??null,publishedAt:entry.publishedAt,htmlUrl:entry.htmlUrl,body:entry.body,bodyPreview:entry.bodyPreview,headline:entry.headline,signals:entry.signals.length>0?entry.signals:undefined}}function lowerEnum(value){return value?.toLowerCase()}function normaliseRegistryPrefix(value){return value.replace(/^([A-Z_]+):/,(prefix)=>prefix.toLowerCase())}function changelogSignalText(body){if(!body)return"";const lines=body.replace(/\r\n/g,`
|
|
113
113
|
`).split(`
|
|
114
114
|
`);const kept=[];let inCommitSection=false;for(const rawLine of lines){const line=rawLine.trim();if(/^#{1,6}\s+commits?\b/i.test(line)){inCommitSection=true;continue}if(/^#{1,6}\s+/.test(line))inCommitSection=false;if(inCommitSection)continue;if(looksLikeCommitListLine(line))continue;kept.push(rawLine)}return kept.join(`
|
|
115
115
|
`)}function looksLikeCommitListLine(line){return/^[-*]\s+[0-9a-f]{7,40}\b/i.test(line)}function matchesSignalTerm(text,term){const lower=text.toLowerCase();if(term==="breaking"||term==="breaks"){if(/\b(no|without|not)\s+breaking\s+changes?\b/i.test(text))return false}return lower.includes(term)}function formatPackageUpgradeReviewTerminal(response,options={}){const useColors=options.useColors===true;const width=normaliseTerminalWidth(options.terminalWidth);const lines=[sectionTitle(`Upgrade review - ${response.reviews.length} ${response.reviews.length===1?"package":"packages"}`,useColors)];if(response.reviews.length>1){appendWrappedText(lines,"Across packages: ",aggregateSummary(response),width)}const reviews=response.reviews.length>1?[...response.reviews].sort((a,b)=>b.changelog.riskCoverage.itemsMustActConfident-a.changelog.riskCoverage.itemsMustActConfident):response.reviews;if(reviews.length>1){appendSection(lines,formatBatchTriage(reviews,options));if(response.filter)appendWrappedText(lines," ",`Changes filter: ${response.filter.changes} (applies to detailed reports; triage shows whole-range totals).`,width," ");if(!options.verbose)return`${lines.join(`
|