@githits/mcp 0.40.1 → 0.41.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.
@@ -1,11 +1,16 @@
1
1
  var EXPECTED_MCP_TOOLS=["quick_start","get_example","search","search_status","list","read","grep","resolve_target","code_diff","pkg_info","pkg_vulns","pkg_deps","pkg_changelog","pkg_upgrade_review","research"];var DEFAULT_TEXT_LIMIT=12000;var TARGET_DETAIL_STATE_PATTERN=/^ {2}(?:(?:indexing|searched|available|unavailable|using):|(?:ready|pending|provisional|older snapshot)$|(?:not found|unresolved|version unavailable|repository ref unresolved|(?:package|repository|site|target) (?:not found|unresolved)):)/;var SMOKE_PACKAGE_VERSION="5.2.1";var SMOKE_PACKAGE_TARGET=`npm:express@${SMOKE_PACKAGE_VERSION}`;var INLINE_SEARCH_QUERY="application path:lib/ intent:production lang:javascript";var SMOKE_TRANSITIVE_VULNERABILITY_TARGET="npm:express@4.17.1";function assert(condition,message){if(!condition){throw new Error(message)}}function parseJson(text,context){try{return JSON.parse(text)}catch(error){const message=error instanceof Error?error.message:"unknown error";throw new Error(`${context}: expected parseable JSON (${message})`)}}function assertNotJson(text,context){try{JSON.parse(text)}catch{return}throw new Error(`${context}: text response unexpectedly parsed as JSON`)}function assertRecord(value,context){assert(value!==null&&typeof value==="object"&&!Array.isArray(value),`${context}: expected object`)}function assertTransitiveVulnerabilityText(text,context){assert(text.includes("Resolved dependencies"),`${context}: missing resolved-dependencies section`);assert(!text.includes("use -v"),`${context}: CLI-native transitive hint leaked into MCP output`);if(text.includes("... (+")){assert(text.includes("use verbose=true or format=json"),`${context}: capped transitive output missing MCP-native hint`)}}function assertTransitiveVulnerabilityJson(value,context){assertRecord(value,context);assertRecord(value.transitive,`${context}.transitive`);assert(value.transitive.scope==="resolved_dependencies",`${context}: unexpected transitive scope`);assert(["affected","non_affecting","unknown","all"].includes(value.transitive.advisoryScope),`${context}: unexpected transitive advisory scope`);assert(value.transitive.withdrawnAdvisoriesIncluded===false,`${context}: transitive withdrawn-advisory flag must be false`);assertRecord(value.transitive.summary,`${context}.transitive.summary`);for(const key of["totalPackagesAnalyzed","packageCount","occurrenceCount"]){assert(typeof value.transitive.summary[key]==="number",`${context}: transitive summary missing numeric ${key}`)}assert(Array.isArray(value.transitive.packages),`${context}: transitive packages must be an array`)}function headerValue(headers,name){if(!headers)return null;if("get"in headers&&typeof headers.get==="function"){return headers.get(name)}const lowerName=name.toLowerCase();for(const[key,value]of Object.entries(headers)){if(key.toLowerCase()===lowerName)return value??null}return null}function resultText(result,context){assert(Array.isArray(result.content),`${context}: expected content array`);const first=result.content[0];assert(first?.type==="text",`${context}: expected text content`);assert(typeof first.text==="string",`${context}: expected text string`);return first.text}function assertCleanErrorEnvelope(result,context){assert(result.isError===true,`${context}: expected MCP error result`);const payload=parseJson(resultText(result,context),context);assertRecord(payload,context);assert(typeof payload.error==="string"&&payload.error.length>0,`${context}: missing error`);assert(typeof payload.code==="string"&&payload.code.length>0,`${context}: missing code`);assert(typeof payload.retryable==="boolean",`${context}: missing retryable`);return payload}function assertHttpUnauthorizedChallenge(metadata,context="unauthenticated HTTP challenge"){assert(metadata.status===401,`${context}: expected HTTP 401`);const challenge=headerValue(metadata.headers,"www-authenticate");assert(typeof challenge==="string"&&challenge.length>0,`${context}: missing WWW-Authenticate header`);assert(/^Bearer\b/i.test(challenge),`${context}: expected Bearer challenge, got ${challenge}`)}function assertDefaultText(result,context){const text=assertToolText(result,context);assert(text.length<DEFAULT_TEXT_LIMIT,`${context}: default text too large (${text.length} chars)`);return text}function assertToolText(result,context){assert(result.isError!==true,`${context}: expected success`);const text=resultText(result,context);assert(text.length>0,`${context}: expected non-empty text`);assertNotJson(text,context);assert(!text.includes("--lifecycle"),`${context}: leaked CLI lifecycle flag`);assert(!text.includes("--verbose"),`${context}: leaked CLI verbose flag`);return text}function listTextFirstPath(text,context){const lines=text.split(`
2
2
  `);assert(lines[0]==="Sources:"&&lines[1]?.startsWith(" - "),`${context}: missing Sources row`);const actionIndex=lines.findIndex((line)=>line.startsWith("Read files: read target="));assert(actionIndex>1,`${context}: missing native read recipe`);const path=lines[actionIndex+1];assert(path!==undefined&&path.length>0,`${context}: missing path`);return path}function listTextContinuation(text,context){const line=text.split(`
3
- `).find((value)=>value.startsWith(" after="));assert(line!==undefined,`${context}: missing after continuation`);const parsed=parseJson(line.slice(" after=".length),context);assert(typeof parsed==="string"&&parsed.length>0,`${context}: invalid after continuation`);return parsed}function assertGrepResult(value,context){assertRecord(value,context);assert(Array.isArray(value.pathWarnings)&&value.pathWarnings.every((warning)=>typeof warning==="string"),`${context}: pathWarnings must contain compact warning strings`);assert(Array.isArray(value.hits),`${context}: hits must be an array`);assert(Array.isArray(value.targets),`${context}: targets must be an array`);assert(Array.isArray(value.unavailableTargets),`${context}: unavailableTargets must be an array`);assert(["COMPLETE","RESUMABLE_LIMIT","NON_RESUMABLE_PARTIAL","FAILED","CURSOR_EXPIRED"].includes(value.traversal),`${context}: unknown traversal state`);assert(value.nextCursor===null||typeof value.nextCursor==="string"&&value.nextCursor.length>0,`${context}: invalid nextCursor`);assert(Number.isSafeInteger(value.totalMatches)&&value.totalMatches>=0,`${context}: invalid totalMatches`);if(value.traversal==="RESUMABLE_LIMIT"){assert(typeof value.nextCursor==="string"&&value.nextCursor.length>0,`${context}: resumable page missing nextCursor`)}const targetByIndex=new Map;for(const[index,target]of value.targets.entries()){assertRecord(target,`${context}.targets[${index}]`);assert(Number.isSafeInteger(target.targetIndex),`${context}.targets[${index}]: invalid targetIndex`);assert(Array.isArray(target.requestedInputIndices)&&target.requestedInputIndices.every(Number.isSafeInteger),`${context}.targets[${index}]: invalid requestedInputIndices`);assert(target.kind==="REPOSITORY"||target.kind==="SITE",`${context}.targets[${index}]: invalid kind`);assert(["UNSPECIFIED","CURRENT","STALE","NOT_AVAILABLE","MISSING_REF","READER_OPEN_FAILED","INCOMPLETE","RESOURCE_LIMIT","VERSION_UNSUPPORTED","READ_FAILED"].includes(target.readiness)&&["COMPLETE","RESUMABLE_LIMIT","NON_RESUMABLE_PARTIAL","FAILED","CURSOR_EXPIRED"].includes(target.traversal),`${context}.targets[${index}]: missing readiness or traversal`);targetByIndex.set(target.targetIndex,target)}for(const[index,hit]of value.hits.entries()){const hitContext=`${context}.hits[${index}]`;assertRecord(hit,hitContext);const scope=targetByIndex.get(hit.targetIndex);assert(scope,`${hitContext}: no matching target status`);assertRecord(hit.read,`${hitContext}.read`);assert(typeof hit.read.target==="string"&&Number.isSafeInteger(hit.read.startLine)&&Number.isSafeInteger(hit.read.endLine),`${hitContext}: incomplete read action`);assertRecord(hit.lineSlice,`${hitContext}.lineSlice`);assert(typeof hit.lineSlice.content==="string"&&Number.isSafeInteger(hit.matchStartByte)&&Number.isSafeInteger(hit.matchEndByte),`${hitContext}: incomplete match evidence`);if(hit.__typename==="GrepRepositoryHit"){assert(scope.kind==="REPOSITORY"&&typeof hit.read.path==="string"&&typeof hit.filePath==="string",`${hitContext}: invalid repository hit or read action`)}else if(hit.__typename==="GrepSiteHit"){assert(scope.kind==="SITE"&&hit.read.path===null&&typeof hit.pageUrl==="string",`${hitContext}: invalid hosted documentation hit or read action`)}else{throw new Error(`${hitContext}: unknown hit type`)}}return value}function grepReadArgs(hit,format){const read=hit.read;return{target:read.target,...typeof read.path==="string"?{path:read.path}:{},start_line:read.startLine,end_line:read.endLine,...format?{format}:{}}}function assertSearchDefaultText(text,context){const lines=text.split(`
3
+ `).find((value)=>value.startsWith(" after="));assert(line!==undefined,`${context}: missing after continuation`);const parsed=parseJson(line.slice(" after=".length),context);assert(typeof parsed==="string"&&parsed.length>0,`${context}: invalid after continuation`);return parsed}function assertGrepResult(value,context){assertRecord(value,context);assert(Array.isArray(value.pathWarnings)&&value.pathWarnings.every((warning)=>typeof warning==="string"),`${context}: pathWarnings must contain compact warning strings`);assert(Array.isArray(value.hits),`${context}: hits must be an array`);assert(Array.isArray(value.targets),`${context}: targets must be an array`);assert(Array.isArray(value.unavailableTargets),`${context}: unavailableTargets must be an array`);assert(["COMPLETE","RESUMABLE_LIMIT","NON_RESUMABLE_PARTIAL","FAILED","CURSOR_EXPIRED"].includes(value.traversal),`${context}: unknown traversal state`);assert(value.nextCursor===null||typeof value.nextCursor==="string"&&value.nextCursor.length>0,`${context}: invalid nextCursor`);assert(Number.isSafeInteger(value.totalMatches)&&value.totalMatches>=0,`${context}: invalid totalMatches`);if(value.traversal==="RESUMABLE_LIMIT"){assert(typeof value.nextCursor==="string"&&value.nextCursor.length>0,`${context}: resumable page missing nextCursor`)}const targetByIndex=new Map;for(const[index,target]of value.targets.entries()){assertRecord(target,`${context}.targets[${index}]`);assert(Number.isSafeInteger(target.targetIndex),`${context}.targets[${index}]: invalid targetIndex`);assert(Array.isArray(target.requestedInputIndices)&&target.requestedInputIndices.every(Number.isSafeInteger),`${context}.targets[${index}]: invalid requestedInputIndices`);assert(target.kind==="REPOSITORY"||target.kind==="SITE",`${context}.targets[${index}]: invalid kind`);assert(["UNSPECIFIED","CURRENT","STALE","NOT_AVAILABLE","MISSING_REF","READER_OPEN_FAILED","INCOMPLETE","RESOURCE_LIMIT","VERSION_UNSUPPORTED","READ_FAILED"].includes(target.readiness)&&["COMPLETE","RESUMABLE_LIMIT","NON_RESUMABLE_PARTIAL","FAILED","CURSOR_EXPIRED"].includes(target.traversal),`${context}.targets[${index}]: missing readiness or traversal`);targetByIndex.set(target.targetIndex,target)}for(const[index,hit]of value.hits.entries()){const hitContext=`${context}.hits[${index}]`;assertRecord(hit,hitContext);const scope=targetByIndex.get(hit.targetIndex);assert(scope,`${hitContext}: no matching target status`);assertRecord(hit.read,`${hitContext}.read`);assert(typeof hit.read.target==="string"&&Number.isSafeInteger(hit.read.startLine)&&Number.isSafeInteger(hit.read.endLine),`${hitContext}: incomplete read action`);assertRecord(hit.lineSlice,`${hitContext}.lineSlice`);assert(typeof hit.lineSlice.content==="string"&&Number.isSafeInteger(hit.matchStartByte)&&Number.isSafeInteger(hit.matchEndByte),`${hitContext}: incomplete match evidence`);if(hit.__typename==="GrepRepositoryHit"){assert(scope.kind==="REPOSITORY"&&typeof hit.read.path==="string"&&typeof hit.filePath==="string",`${hitContext}: invalid repository hit or read action`)}else if(hit.__typename==="GrepSiteHit"){assert(scope.kind==="SITE"&&hit.read.path===null&&typeof hit.pageUrl==="string",`${hitContext}: invalid hosted documentation hit or read action`)}else{throw new Error(`${hitContext}: unknown hit type`)}}return value}function grepReadArgs(hit,format){const read=hit.read;return{target:read.target,...typeof read.path==="string"?{path:read.path}:{},start_line:read.startLine,end_line:read.endLine,...format?{format}:{}}}function assertSearchDefaultText(text,context){const sources=text.split(`
4
+ Sources:
5
+ `)[1]?.split(`
6
+
7
+ `)[0]?.replace(/\s+/g," ")??"";assert(!/(?:\(|, )(?:code|symbols|docs|repository docs|hosted documentation|no results(?: on this page)?)(?:,|\))/.test(sources),`${context}: Sources contains redundant category or zero-hit qualifiers`);const lines=text.split(`
4
8
  `);let pathOnlyBlock=false;for(const line of lines){if(/^\[\d+\] /.test(line)){pathOnlyBlock=/\[repo (?:code|doc), path match\]$/.test(line)}else if(pathOnlyBlock){assert(!/^\s*>?\s*\d+ \|/.test(line),`${context}: path-only hit contains an arbitrary source snippet`)}}const formatterLines=searchFormatterLines(lines);const formatterText=formatterLines.join(`
5
9
  `);const firstLine=lines[0]?.trim()??"";assert(firstLine.length>0,`${context}: missing outcome first line`);assert(/^(?:Found \d+ |No results? )/.test(firstLine),`${context}: missing outcome headline`);assert(!firstLine.startsWith("search |")&&!firstLine.startsWith("search_status |"),`${context}: legacy header precedes outcome`);assert(!formatterLines.some((line)=>/^status\s*:/i.test(line.trim())),`${context}: duplicated lifecycle status line`);assert(!formatterLines.some((line)=>/^Search\s+\S+\s+\|/.test(line)),`${context}: separate Search <ref> session summary`);const outcomeLines=formatterLines.filter((line)=>/^(?:Found \d+ |No results? )/.test(line));assert(outcomeLines.length===1,`${context}: duplicate outcome lines`);assert(!formatterText.includes("searchRef="),`${context}: leaked searchRef=`);assert(!formatterText.includes("indexingRef"),`${context}: leaked indexingRef`);const forbiddenSections=["Ready:","Waiting:","Available but not searched:","Indexed alternatives:"];for(const section of forbiddenSections){assert(!lines.some((line)=>line.startsWith(section)),`${context}: legacy flat section ${section}`)}assert(!lines.some((line)=>line==="Evidence may change."),`${context}: vague evidence policy prose`);assert(!lines.some((line)=>line.startsWith("Do not repeat")),`${context}: repeat policy prose`);assert(!lines.some((line)=>line.startsWith("Do not poll")),`${context}: poll policy prose`);const footerLabels=["Read:","More results:","Follow-up:"];const presentFooters=formatterLines.filter((line)=>footerLabels.includes(line));assert(new Set(presentFooters).size===presentFooters.length,`${context}: duplicated footer section`);assert(presentFooters.join()===footerLabels.filter((label)=>presentFooters.includes(label)).join(),`${context}: footer sections out of order`);assert(!firstLine.includes("|")&&!/partial|interim|ready|offset/.test(firstLine),`${context}: headline must contain only the outcome`);const hasReadinessText=formatterLines.some((line)=>TARGET_DETAIL_STATE_PATTERN.test(line));if(hasReadinessText){assert(formatterLines.some((line)=>/^-\s+\S/.test(line)),`${context}: readiness details must be grouped under a target`)}const statusActions=formatterLines.filter((line)=>line.startsWith(" search_status "));const searchRefOccurrences=formatterText.match(/search_ref=/g)?.length??0;assert(statusActions.length<=1&&searchRefOccurrences===statusActions.length,`${context}: expected at most one native status action`);const statusAction=statusActions[0];if(statusAction){assert(formatterLines.includes("Follow-up:")&&formatterLines.indexOf("Follow-up:")<formatterLines.indexOf(statusAction),`${context}: status action must be in Follow-up`);assert(/^ {2}search_status search_ref="[^"]+" wait_timeout_ms=\d+$/.test(statusAction),`${context}: invalid native status action`)}assert(!formatterText.includes("githits search-status ")&&!formatterText.includes("githits read ")&&!formatterText.includes("githits code read ")&&!formatterText.includes("githits docs read ")&&!formatterText.includes(" --wait ")&&!formatterText.includes(" --offset "),`${context}: CLI command syntax leaked into MCP output`);assert(hasHumanSearchHitLocator(lines)||hasTargetRecovery(formatterLines)||formatterLines.includes("Follow-up:")||formatterLines.includes("More results:"),`${context}: missing usable result locator or status follow-up`)}function hasTargetRecovery(lines){return lines.some((line,index)=>{if(!/^ {2}(?:Fix|Try):\s+\S/.test(line))return false;for(let previousIndex=index-1;previousIndex>=0;previousIndex-=1){const previous=lines[previousIndex];if(!previous||previous.trim()==="")continue;if(/^-\s+\S/.test(previous))return true;if(previous.startsWith(" "))continue;return false}return false})}function hasHumanSearchHitLocator(lines){return lines.some((line,index)=>{const docsMatch=/^\[\d+\]\s+(\S+)\s+\[docs page\]\s+(.+)$/.exec(line);if(docsMatch){const pageId=docsMatch[1];const docsDetails=docsMatch[2];if(!pageId||pageId==="page ID unavailable"||!docsDetails){return false}const firstDivider=docsDetails.indexOf(" - ");if(firstDivider<=0)return false;const sourceAndTitle=docsDetails.slice(firstDivider+3);const secondDivider=sourceAndTitle.indexOf(" - ");if(secondDivider>0){const source=sourceAndTitle.slice(0,secondDivider).trim();const title=sourceAndTitle.slice(secondDivider+3).trim();return source.length>0&&(title.length>0||hasWrappedHitTitle(lines,index))}if(!sourceAndTitle.endsWith(" -"))return false;const source=sourceAndTitle.slice(0,-2).trim();return source.length>0&&hasWrappedHitTitle(lines,index)}const match=/^\[\d+\]\s+(.+?)\s+\[(repo doc|repo code|repo symbol)(?:, path match)?\](?: -(?: (.*))?)?$/.exec(line);if(!match)return false;const locatorText=match[1];if(!locatorText)return false;const locator=locatorText.trim().split(/\s+/);if(locator.length>=2&&!locatorText.trim().endsWith("location unavailable")&&locator.every((part)=>part.length>0)){const title=match[3];return title===undefined?!line.endsWith(" -")||hasWrappedHitTitle(lines,index):title.trim().length>0||hasWrappedHitTitle(lines,index)}return false})}function hasWrappedHitTitle(lines,index){const titleLine=lines[index+1];return titleLine?.startsWith(" ")===true&&titleLine.trim().length>0}function searchFormatterLines(lines){let inHit=false;return lines.filter((line)=>{if(/^\[\d+\]\s/.test(line)){inHit=true;return true}if(inHit&&line.length>0&&!line.startsWith(" "))inHit=false;return!inHit})}function assertJsonResult(result,context){assert(result.isError!==true,`${context}: expected success`);return parseJson(resultText(result,context),context)}function assertErrorCode(result,context,code){const envelope=assertCleanErrorEnvelope(result,context);assert(envelope.code===code,`${context}: expected ${code}, got ${envelope.code}`)}function assertInlineSearchSuccess(value,expectedQuery,context){assertRecord(value,context);assertRecord(value.query,`${context}: query`);assert(value.query.raw===expectedQuery,`${context}: raw query mismatch`);assert(Array.isArray(value.results)&&value.results.length>0,`${context}: missing ranked results`);for(const[index,result]of value.results.entries()){assertRecord(result,`${context}: results[${index}]`);assertRecord(result.locator,`${context}: results[${index}].locator`);const filePath=result.locator.filePath;assert(typeof filePath==="string"&&filePath.startsWith("lib/")&&filePath.endsWith(".js"),`${context}: result escaped JavaScript lib/ scope`)}if("warnings"in value){assert(Array.isArray(value.warnings),`${context}: warnings must be an array`)}if(!("sourceStatus"in value))return;assert(Array.isArray(value.sourceStatus),`${context}: sourceStatus must be an array`);const unsupportedFeatures=[];for(const[index,entry]of value.sourceStatus.entries()){assertRecord(entry,`${context}: sourceStatus[${index}] must be an object`);for(const field of["ignoredQueryFeatures","incompatibleQueryFeatures"]){const features=entry[field];if(features===undefined)continue;assert(Array.isArray(features),`${context}: sourceStatus[${index}].${field} must be an array`);for(const feature of features){assert(typeof feature==="string",`${context}: sourceStatus[${index}].${field} must contain strings`);unsupportedFeatures.push(feature)}}}if(unsupportedFeatures.length===0)return;assert(Array.isArray(value.warnings),`${context}: unsupported qualifiers must be surfaced in warnings`);const warningText=value.warnings.join(" ").toLowerCase();for(const feature of unsupportedFeatures){assert(warningText.includes(feature.toLowerCase()),`${context}: qualifier ${feature} was lost without a warning`)}}function assertInlineSearchError(result,context){const envelope=assertCleanErrorEnvelope(result,context);assert(envelope.code==="INVALID_ARGUMENT",`${context}: expected INVALID_ARGUMENT, got ${envelope.code}`);assert(envelope.retryable===false,`${context}: error must not be retryable`);for(const field of["searchRef","search_ref","continuation"]){assert(!(field in envelope),`${context}: error exposed ${field}`)}}async function callTool(caller,name,args){return await caller.callTool(name,args)}async function callToolText(caller,name,args){const result=await caller.callTool(name,args);const text=resultText(result,name);if(result.isError===true){throw new Error(text)}return text}async function assertLiveOrAuthRequired(caller,logger){const result=await callTool(caller,"pkg_info",{target:"npm:express",format:"json"});if(result.isError===true){const envelope=assertCleanErrorEnvelope(result,"pkg_info auth probe");assert(envelope.code==="AUTH_REQUIRED",`auth probe returned unexpected code ${envelope.code}`);const authAction=envelope.details?.action;assert(typeof authAction==="string"&&authAction.trim().length>0,"pkg_info auth probe: missing authentication action");for(const[format,label]of[[undefined,"omitted"],["text","text"]]){const textResult=await callTool(caller,"pkg_info",{target:"npm:express",...format===undefined?{}:{format}});const context=`pkg_info ${label} auth probe`;assert(textResult.isError===true,`${context}: expected MCP error result`);const text=resultText(textResult,context);assertNotJson(text,context);assert(text.includes(authAction),`${context}: missing authentication action from JSON probe`)}logger.log("AUTH_REQUIRED: live smoke skipped");return false}return true}function isResolveDirectTargetUnwarned(output,target){if(/^Warning:/m.test(output))return false;const escapedTarget=target.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");const candidatePattern=new RegExp(`^(?: {2}\\d+\\. | {7})${escapedTarget}(?:\\s|$)`);const lines=output.split(`
6
- `);const candidateIndex=lines.findIndex((line)=>candidatePattern.test(line));if(candidateIndex<0)return false;const candidateLine=lines[candidateIndex]??"";const nested=candidateLine.startsWith(" ");if(candidateLine.includes(" · related ")||candidateLine.includes("[related;")){return false}const detailIndent=nested?" ":" ";for(let index=candidateIndex+1;index<lines.length;index+=1){const line=lines[index]??"";if(line.trim()==="Related targets:")break;if(!line.startsWith(detailIndent))break;if(line.includes("Warning:"))return false}return true}function assertMcpResolveText(resolveTextBody){assert(resolveTextBody.includes("npm:express")&&!resolveTextBody.includes("githits ")&&!resolveTextBody.includes("--"),"resolve text should include MCP-native candidate guidance");const directTarget=resolveTextBody.match(/Next: pass the returned target "([^"]+)"/)?.[1];if(directTarget){assert(isResolveDirectTargetUnwarned(resolveTextBody,directTarget),"direct resolve action should target a listed direct candidate without a warning");return}if(resolveTextBody.includes("Warning:")){assert(!resolveTextBody.includes("Next:"),"malicious-blocked resolve text should omit the normal next action")}else if(resolveTextBody.includes("Ambiguous:")){assert(resolveTextBody.includes("never auto-select")&&resolveTextBody.includes("explicitly choose a candidate"),"ambiguous resolve text should require an explicit choice")}else{assert(resolveTextBody.includes("never auto-select the best match")&&resolveTextBody.includes("explicitly choose a candidate"),"unconfirmed resolve text should require an explicit choice")}}async function runLiveSmoke(caller){for(const probe of[{tool:"pkg_deps",target:"npm:express@99.99.99",code:"VERSION_NOT_FOUND",fact:"availablePackageVersions"},{tool:"list",target:"github:expressjs/express@v99.99.99-nope",code:"REF_NOT_FOUND",fact:"suggestedRefs"}]){const result=await callTool(caller,probe.tool,{target:probe.target});assert(result.isError===true,"recovery probe must fail for the original target");const text=resultText(result,"version/ref recovery text");assert(text.includes(`Retry ${probe.tool} with target=`),"recovery probe missing native argument correction");const envelope=assertCleanErrorEnvelope(await callTool(caller,probe.tool,{target:probe.target,format:"json"}),"version/ref recovery JSON");assert(envelope.code===probe.code,"recovery probe lost backend error code");const details=envelope.details;const alternatives=details?.[probe.fact];assert(Array.isArray(alternatives)&&alternatives.length>0,"recovery probe dropped structured alternatives");assert(typeof details?.action==="string"&&details.action.startsWith(`Retry ${probe.tool} with target=`),"recovery probe JSON missing native action")}await runResolveSmoke(caller);const diffArgs={target:"npm:express",from:"5.2.0",to:"5.2.1",max_files:2};const diffText=assertDefaultText(await callTool(caller,"code_diff",diffArgs),"code_diff default");assert(diffText.includes("Resolved endpoints:")&&diffText.includes("Scope: repository"),"code_diff default missing exact resolution or scope");const diffJson=assertJsonResult(await callTool(caller,"code_diff",{...diffArgs,format:"json"}),"code_diff json");assertRecord(diffJson,"code_diff json");assertRecord(diffJson.from,"code_diff from");assertRecord(diffJson.to,"code_diff to");assertRecord(diffJson.scope,"code_diff scope");assert(diffJson.view==="name-status"&&diffJson.from.requested===diffArgs.from&&diffJson.to.requested===diffArgs.to&&diffJson.scope.status==="repository","code_diff default projection or identity mismatch");assert(Array.isArray(diffJson.files)&&diffJson.files.length>0&&diffJson.files.length<=2&&diffJson.hasMoreFiles===true,"code_diff file bound or truncation missing");const diffPatch=assertJsonResult(await callTool(caller,"code_diff",{...diffArgs,view:"patch",path_glob:"lib/utils.js",format:"json"}),"code_diff scoped patch");assertRecord(diffPatch,"code_diff scoped patch");assert(diffPatch.view==="patch"&&Array.isArray(diffPatch.files)&&diffPatch.files.length===1,"code_diff scoped patch missing filtered file");const diffFile=diffPatch.files[0];assertRecord(diffFile,"code_diff patch file");assert(diffFile.path==="lib/utils.js"&&typeof diffFile.patch==="string"&&diffFile.patch.startsWith("diff --git"),"code_diff scoped patch missing unified content");const exampleText=assertDefaultText(await callTool(caller,"get_example",{query:"express hello world",language:"javascript"}),"get_example default");assert(exampleText.includes("solution_id:"),"get_example default missing solution_id hint");const exampleJson=assertJsonResult(await callTool(caller,"get_example",{query:"express hello world",language:"javascript",format:"json"}),"get_example json");assertRecord(exampleJson,"get_example json");assert(typeof exampleJson.result==="string","get_example json missing result");const pkgInfoText=assertDefaultText(await callTool(caller,"pkg_info",{target:"npm:express"}),"pkg_info default");assert(pkgInfoText.includes("express"),"pkg_info default missing package name");assert(pkgInfoText.includes("Repository")&&pkgInfoText.includes("stars"),"pkg_info default missing repository popularity");assert(pkgInfoText.includes("Vulnerabilities"),"pkg_info default missing vulnerability status");assert(pkgInfoText.includes("Latest:"),"pkg_info default missing latest vulnerability scope");assert(pkgInfoText.includes("History:"),"pkg_info default missing package-wide vulnerability history scope");assert(!pkgInfoText.includes("Install")&&!pkgInfoText.includes("Usage"),"pkg_info default should not include quickstart fields");const pkgInfoJson=assertJsonResult(await callTool(caller,"pkg_info",{target:"npm:express",format:"json"}),"pkg_info json");let rustVersion;for(const target of["crates:serde","cargo:serde"]){const context=`pkg_info ${target}`;const metadata=assertJsonResult(await callTool(caller,"pkg_info",{target,format:"json"}),context);assertRecord(metadata,context);assert(metadata.registry==="crates"&&metadata.name==="serde",`${context}: expected canonical crates identity`);assert(typeof metadata.version==="string",`${context}: missing version`);if(rustVersion!==undefined)assert(metadata.version===rustVersion,`${context}: alias version mismatch`);rustVersion=metadata.version}assertRecord(pkgInfoJson,"pkg_info json");assert(pkgInfoJson.registry==="npm","pkg_info json registry mismatch");assert(pkgInfoJson.name==="express","pkg_info json name mismatch");assert(typeof pkgInfoJson.version==="string","pkg_info json missing version");assert(typeof pkgInfoJson.latestVersion==="string","pkg_info json missing registry latest version");assert(typeof pkgInfoJson.versionCount==="number","pkg_info json missing version count");assertRecord(pkgInfoJson.downloads,"pkg_info json downloads");assert(typeof pkgInfoJson.downloads.refreshedAt==="string","pkg_info json missing download refresh date");assertRecord(pkgInfoJson.advisoryHistory,"pkg_info json advisory history");assert(typeof pkgInfoJson.advisoryHistory.total==="number","pkg_info json missing advisory history count");assert(!("install"in pkgInfoJson)&&!("usage"in pkgInfoJson),"pkg_info json should not include quickstart fields");const depsText=assertDefaultText(await callTool(caller,"pkg_deps",{target:"npm:express"}),"pkg_deps default");assert(depsText.includes("Runtime dependencies:"),"pkg_deps default missing runtime heading");assert(depsText.includes('pass lifecycle="all"'),"pkg_deps default missing MCP-native lifecycle hint");const depsAllText=assertDefaultText(await callTool(caller,"pkg_deps",{target:"npm:express",lifecycle:"all"}),"pkg_deps lifecycle all");assert(depsAllText.includes("Dependency groups:"),"pkg_deps lifecycle all missing groups heading");assert(!depsAllText.includes("Hidden groups:"),"pkg_deps lifecycle all still hides groups");const depsJson=assertJsonResult(await callTool(caller,"pkg_deps",{target:"npm:express",format:"json"}),"pkg_deps json");assertRecord(depsJson,"pkg_deps json");assertRecord(depsJson.runtime,"pkg_deps json runtime");const depsIssuesText=assertDefaultText(await callTool(caller,"pkg_deps",{target:"npm:express",include_issues:true}),"pkg_deps issues default");assert(depsIssuesText.includes("Dependency issues"),"pkg_deps issues default missing issue heading");const depsIssuesJson=assertJsonResult(await callTool(caller,"pkg_deps",{target:"npm:express",include_issues:true,format:"json"}),"pkg_deps issues json");assertRecord(depsIssuesJson,"pkg_deps issues json");assert(!("transitive"in depsIssuesJson),"pkg_deps issues json should not expose ordinary transitive output");assertRecord(depsIssuesJson.issues,"pkg_deps issues json issues");assertRecord(depsIssuesJson.issues.scope,"pkg_deps issues json scope");assert(depsIssuesJson.issues.scope.mode==="full","pkg_deps issues json should report full scope");for(const category of["deprecated","outdated","duplicates","conflicts"]){assertRecord(depsIssuesJson.issues[category],`pkg_deps issues json ${category}`);assert(typeof depsIssuesJson.issues[category].count==="number",`pkg_deps issues json ${category} missing count`);assert(Array.isArray(depsIssuesJson.issues[category].items),`pkg_deps issues json ${category} missing items`)}const vulnsText=assertDefaultText(await callTool(caller,"pkg_vulns",{target:"npm:express"}),"pkg_vulns default");assert(vulnsText.includes("express")||vulnsText.includes("vulnerab"),"pkg_vulns default missing context");assert(!vulnsText.includes("use -v"),"pkg_vulns leaked CLI -v hint");const transitiveVulnsText=assertDefaultText(await callTool(caller,"pkg_vulns",{target:SMOKE_TRANSITIVE_VULNERABILITY_TARGET,include_transitive:true}),"pkg_vulns transitive default");assertTransitiveVulnerabilityText(transitiveVulnsText,"pkg_vulns transitive default");const transitiveVulnsJson=assertJsonResult(await callTool(caller,"pkg_vulns",{target:SMOKE_TRANSITIVE_VULNERABILITY_TARGET,include_transitive:true,advisory_scope:"all",format:"json"}),"pkg_vulns transitive json");assertTransitiveVulnerabilityJson(transitiveVulnsJson,"pkg_vulns transitive json");assertRecord(transitiveVulnsJson,"pkg_vulns transitive json");assert(transitiveVulnsJson.transitive.advisoryScope==="all","pkg_vulns transitive json did not apply all advisory scope");const filteredVulnsText=assertDefaultText(await callTool(caller,"pkg_vulns",{target:"npm:lodash@4.17.20",min_severity:"high"}),"pkg_vulns filtered default");assert(filteredVulnsText.includes("Filter severity >= high"),"pkg_vulns filtered default missing filter echo");assert(!filteredVulnsText.includes("use -v"),"pkg_vulns filtered default leaked CLI -v hint");const vulnsJson=assertJsonResult(await callTool(caller,"pkg_vulns",{target:"npm:express",format:"json"}),"pkg_vulns json");assertRecord(vulnsJson,"pkg_vulns json");assert("summary"in vulnsJson||"advisories"in vulnsJson,"pkg_vulns json missing vulnerability data");const filteredVulnsJson=assertJsonResult(await callTool(caller,"pkg_vulns",{target:"npm:lodash@4.17.20",min_severity:"high",format:"json"}),"pkg_vulns filtered json");assertRecord(filteredVulnsJson,"pkg_vulns filtered json");assertRecord(filteredVulnsJson.filter,"pkg_vulns filtered json filter");assert(filteredVulnsJson.filter.minSeverity==="high","pkg_vulns filtered json missing severity filter echo");const scopedVulnsText=assertDefaultText(await callTool(caller,"pkg_vulns",{target:"npm:express",advisory_scope:"non_affecting"}),"pkg_vulns scoped default");assert(scopedVulnsText.includes("Scope non-affecting advisories only"),"pkg_vulns scoped default missing scope echo");assert(scopedVulnsText.includes("No active vulnerabilities affect this version"),"pkg_vulns scoped default missing current-risk statement");assert(!scopedVulnsText.includes("use -v"),"pkg_vulns scoped default leaked CLI -v hint");const scopedVulnsJson=assertJsonResult(await callTool(caller,"pkg_vulns",{target:"npm:express",advisory_scope:"non_affecting",format:"json"}),"pkg_vulns scoped json");assertRecord(scopedVulnsJson,"pkg_vulns scoped json");assertRecord(scopedVulnsJson.filter,"pkg_vulns scoped json filter");assert(scopedVulnsJson.filter.advisoryScope==="non_affecting","pkg_vulns scoped json missing advisory scope echo");const unknownVulnsText=assertDefaultText(await callTool(caller,"pkg_vulns",{target:"npm:lodash@4.17.20",advisory_scope:"unknown"}),"pkg_vulns unknown scope");assert(unknownVulnsText.includes("Scope unknown"),"pkg_vulns unknown scope missing scope echo");const unknownVulnsJson=assertJsonResult(await callTool(caller,"pkg_vulns",{target:"npm:lodash@4.17.20",advisory_scope:"unknown",format:"json"}),"pkg_vulns unknown json");assertRecord(unknownVulnsJson,"pkg_vulns unknown json");assertRecord(unknownVulnsJson.summary,"pkg_vulns unknown summary");assert(typeof unknownVulnsJson.summary.unknownVulnerabilityCount==="number","pkg_vulns missing unknown count");assert(typeof unknownVulnsJson.summary.assessmentStatus==="string","pkg_vulns missing assessment status in JSON");const transitiveUnknown=assertJsonResult(await callTool(caller,"pkg_vulns",{target:"pypi:torchvision@0.20.1",advisory_scope:"unknown",include_transitive:true,format:"json"}),"pkg_vulns transitive unknown");assertRecord(transitiveUnknown,"pkg_vulns transitive unknown");assertRecord(transitiveUnknown.transitive,"pkg_vulns transitive unknown audit");assertRecord(transitiveUnknown.transitive.summary,"pkg_vulns transitive unknown summary");assert(typeof transitiveUnknown.transitive.summary.unknownCount==="number","pkg_vulns missing transitive unknown count");assert(transitiveUnknown.transitive.advisoryScope==="unknown","pkg_vulns missing transitive unknown scope");assertTransitiveVulnerabilityJson(transitiveUnknown,"pkg_vulns transitive unknown");assert(Array.isArray(transitiveUnknown.transitive.packages),"pkg_vulns missing packages");for(const pkg of transitiveUnknown.transitive.packages){assertRecord(pkg,"pkg_vulns unknown package");assert(Array.isArray(pkg.occurrences),"pkg_vulns missing occurrences");for(const row of pkg.occurrences){assertRecord(row,"pkg_vulns unknown occurrence");assert(row.affectsResolvedVersion===false,"pkg_vulns unknown row claims a match");assert(typeof row.assessmentStatus==="string","pkg_vulns missing occurrence status");assert(Array.isArray(row.assessmentReasons),"pkg_vulns missing occurrence reasons")}}const changelogText=assertToolText(await callTool(caller,"pkg_changelog",{target:"npm:express",limit:1}),"pkg_changelog default");assert(!changelogText.includes("--verbose"),"pkg_changelog default leaked CLI verbose flag");if(changelogText.includes("more lines")||changelogText.includes("full bodies")){assert(changelogText.includes("pass verbatim=true"),"pkg_changelog truncation hint is not MCP-native")}const changelogBodyLinesText=assertDefaultText(await callTool(caller,"pkg_changelog",{target:"npm:express",limit:2,body_lines:3}),"pkg_changelog body_lines");if(changelogBodyLinesText.includes("more lines")||changelogBodyLinesText.includes("full bodies")){assert(changelogBodyLinesText.includes("pass verbatim=true"),"pkg_changelog body_lines missing MCP-native truncation hint")}assert(!changelogBodyLinesText.includes("--verbose"),"pkg_changelog body_lines leaked CLI verbose flag");const changelogFullBodiesText=assertToolText(await callTool(caller,"pkg_changelog",{target:"npm:express",limit:2,body_lines:3,verbatim:true}),"pkg_changelog verbose overrides preview controls");assert(!changelogFullBodiesText.includes("pass verbatim=true"),"pkg_changelog verbose still truncated body previews");const changelogJson=assertJsonResult(await callTool(caller,"pkg_changelog",{target:"npm:express",limit:1,format:"json"}),"pkg_changelog json");assertRecord(changelogJson,"pkg_changelog json");assertRecord(changelogJson.entries,"pkg_changelog json entries");assertRecord(changelogJson.statements,"pkg_changelog json statements");assert(Array.isArray(changelogJson.statements.items),"pkg_changelog json missing parsed statements");assert(Array.isArray(changelogJson.statements.coverage),"pkg_changelog json missing coverage");assert(Array.isArray(changelogJson.entries.items)&&changelogJson.entries.items.every((entry)=>typeof entry==="object"&&entry!==null&&!("body"in entry)),"pkg_changelog default JSON over-fetched note bodies");const filteredChangelog=assertJsonResult(await callTool(caller,"pkg_changelog",{target:"npm:express@5.2.1",changes:"actionable",format:"json"}),"pkg_changelog actionable");assertRecord(filteredChangelog,"pkg_changelog actionable");assertRecord(filteredChangelog.statements,"pkg_changelog filtered statements");assert(Array.isArray(filteredChangelog.statements.items)&&filteredChangelog.statements.items.every((item)=>typeof item==="object"&&item!==null&&("classification"in item)&&typeof item.classification==="object"&&item.classification!==null&&("tier"in item.classification)&&item.classification.tier==="must_act"),"pkg_changelog actionable includes another tier");const timelineChangelog=assertJsonResult(await callTool(caller,"pkg_changelog",{target:"npm:express",limit:1,omit_bodies:true,changes:"ignored",format:"json"}),"pkg_changelog timeline-only");assertRecord(timelineChangelog,"pkg_changelog timeline-only");assert(!("statements"in timelineChangelog),"pkg_changelog timeline-only classified notes");const changelogExact=assertJsonResult(await callTool(caller,"pkg_changelog",{target:"npm:express@5.2.1",format:"json"}),"pkg_changelog exact json");assertRecord(changelogExact,"pkg_changelog exact json");assert(changelogExact.mode==="exact","pkg_changelog exact json mode");const exactEntries=changelogExact.entries;assert(exactEntries?.items?.[0]?.version==="5.2.1","pkg_changelog exact json resolved version");assert(typeof exactEntries?.items?.[0]?.hasChangelog==="boolean","pkg_changelog exact json missing hasChangelog");const changelogRepo=await callTool(caller,"pkg_changelog",{target:"github:expressjs/express",format:"json"});const changelogRepoEnvelope=assertCleanErrorEnvelope(changelogRepo,"pkg_changelog repository target");assert(changelogRepoEnvelope.code==="INVALID_ARGUMENT",`pkg_changelog repository target: expected INVALID_ARGUMENT, got ${changelogRepoEnvelope.code}`);const changelogTimeline=assertDefaultText(await callTool(caller,"pkg_changelog",{target:"npm:express",limit:2,omit_bodies:true}),"pkg_changelog timeline");assert(!changelogTimeline.includes("What's Changed"),"pkg_changelog omit_bodies=true still emitted bodies");const upgradeReviewText=assertToolText(await callTool(caller,"pkg_upgrade_review",{registry:"npm",package_name:"express",current_version:"5.0.0",target_version:"5.2.1",skip_transitive_security:true}),"pkg_upgrade_review default");const upgradeReviewFirstLine=upgradeReviewText.split(`
10
+ `);const candidateIndex=lines.findIndex((line)=>candidatePattern.test(line));if(candidateIndex<0)return false;const candidateLine=lines[candidateIndex]??"";const nested=candidateLine.startsWith(" ");if(candidateLine.includes(" · related ")||candidateLine.includes("[related;")){return false}const detailIndent=nested?" ":" ";for(let index=candidateIndex+1;index<lines.length;index+=1){const line=lines[index]??"";if(line.trim()==="Related targets:")break;if(!line.startsWith(detailIndent))break;if(line.includes("Warning:"))return false}return true}function assertMcpResolveText(resolveTextBody){assert(resolveTextBody.includes("npm:express")&&!resolveTextBody.includes("githits ")&&!resolveTextBody.includes("--"),"resolve text should include MCP-native candidate guidance");const directTarget=resolveTextBody.match(/Next: pass the returned target "([^"]+)"/)?.[1];if(directTarget){assert(isResolveDirectTargetUnwarned(resolveTextBody,directTarget),"direct resolve action should target a listed direct candidate without a warning");return}if(resolveTextBody.includes("Warning:")){assert(!resolveTextBody.includes("Next:"),"malicious-blocked resolve text should omit the normal next action")}else if(resolveTextBody.includes("Ambiguous:")){assert(resolveTextBody.includes("never auto-select")&&resolveTextBody.includes("explicitly choose a candidate"),"ambiguous resolve text should require an explicit choice")}else{assert(resolveTextBody.includes("never auto-select the best match")&&resolveTextBody.includes("explicitly choose a candidate"),"unconfirmed resolve text should require an explicit choice")}}async function runLiveSmoke(caller){for(const probe of[{tool:"pkg_deps",target:"npm:express@99.99.99",code:"VERSION_NOT_FOUND",fact:"availablePackageVersions"},{tool:"list",target:"github:expressjs/express@v99.99.99-nope",code:"REF_NOT_FOUND",fact:"suggestedRefs"}]){const result=await callTool(caller,probe.tool,{target:probe.target});assert(result.isError===true,"recovery probe must fail for the original target");const text=resultText(result,"version/ref recovery text");assert(text.includes(`Retry ${probe.tool} with target=`),"recovery probe missing native argument correction");const envelope=assertCleanErrorEnvelope(await callTool(caller,probe.tool,{target:probe.target,format:"json"}),"version/ref recovery JSON");assert(envelope.code===probe.code,"recovery probe lost backend error code");const details=envelope.details;const alternatives=details?.[probe.fact];assert(Array.isArray(alternatives)&&alternatives.length>0,"recovery probe dropped structured alternatives");assert(typeof details?.action==="string"&&details.action.startsWith(`Retry ${probe.tool} with target=`),"recovery probe JSON missing native action")}await runResolveSmoke(caller);const diffArgs={target:"npm:express",from:"5.2.0",to:"5.2.1",max_files:2};const diffText=assertDefaultText(await callTool(caller,"code_diff",diffArgs),"code_diff default");assert(diffText.includes("Resolved endpoints:")&&diffText.includes("Scope: repository"),"code_diff default missing exact resolution or scope");const diffJson=assertJsonResult(await callTool(caller,"code_diff",{...diffArgs,format:"json"}),"code_diff json");assertRecord(diffJson,"code_diff json");assertRecord(diffJson.from,"code_diff from");assertRecord(diffJson.to,"code_diff to");assertRecord(diffJson.scope,"code_diff scope");assert(diffJson.view==="name-status"&&diffJson.from.requested===diffArgs.from&&diffJson.to.requested===diffArgs.to&&diffJson.scope.status==="repository","code_diff default projection or identity mismatch");assert(Array.isArray(diffJson.files)&&diffJson.files.length>0&&diffJson.files.length<=2&&diffJson.hasMoreFiles===true,"code_diff file bound or truncation missing");const diffPatch=assertJsonResult(await callTool(caller,"code_diff",{...diffArgs,view:"patch",path_glob:"lib/utils.js",format:"json"}),"code_diff scoped patch");assertRecord(diffPatch,"code_diff scoped patch");assert(diffPatch.view==="patch"&&Array.isArray(diffPatch.files)&&diffPatch.files.length===1,"code_diff scoped patch missing filtered file");const diffFile=diffPatch.files[0];assertRecord(diffFile,"code_diff patch file");assert(diffFile.path==="lib/utils.js"&&typeof diffFile.patch==="string"&&diffFile.patch.startsWith("diff --git"),"code_diff scoped patch missing unified content");const exampleText=assertDefaultText(await callTool(caller,"get_example",{query:"express hello world",language:"javascript"}),"get_example default");assert(exampleText.includes("solution_id:"),"get_example default missing solution_id hint");const exampleJson=assertJsonResult(await callTool(caller,"get_example",{query:"express hello world",language:"javascript",format:"json"}),"get_example json");assertRecord(exampleJson,"get_example json");assert(typeof exampleJson.result==="string","get_example json missing result");const pkgInfoText=assertDefaultText(await callTool(caller,"pkg_info",{target:"npm:express"}),"pkg_info default");assert(pkgInfoText.includes("express"),"pkg_info default missing package name");assert(pkgInfoText.includes("Repository")&&pkgInfoText.includes("stars"),"pkg_info default missing repository popularity");assert(pkgInfoText.includes("Vulnerabilities"),"pkg_info default missing vulnerability status");assert(pkgInfoText.includes("Latest:"),"pkg_info default missing latest vulnerability scope");assert(pkgInfoText.includes("History:"),"pkg_info default missing package-wide vulnerability history scope");assert(!pkgInfoText.includes("Install")&&!pkgInfoText.includes("Usage"),"pkg_info default should not include quickstart fields");assert(!pkgInfoText.includes("Lifecycle checks:")&&!pkgInfoText.includes("Lifecycle unavailable"),"pkg_info default should omit lifecycle diagnostics");const pkgInfoJson=assertJsonResult(await callTool(caller,"pkg_info",{target:"npm:express",format:"json"}),"pkg_info json");let rustVersion;for(const target of["crates:serde","cargo:serde"]){const context=`pkg_info ${target}`;const metadata=assertJsonResult(await callTool(caller,"pkg_info",{target,format:"json"}),context);assertRecord(metadata,context);assert(metadata.registry==="crates"&&metadata.name==="serde",`${context}: expected canonical crates identity`);assert(typeof metadata.version==="string",`${context}: missing version`);if(rustVersion!==undefined)assert(metadata.version===rustVersion,`${context}: alias version mismatch`);rustVersion=metadata.version}assertRecord(pkgInfoJson,"pkg_info json");assert(pkgInfoJson.registry==="npm","pkg_info json registry mismatch");assert(pkgInfoJson.name==="express","pkg_info json name mismatch");assert(typeof pkgInfoJson.version==="string","pkg_info json missing version");assert(typeof pkgInfoJson.latestVersion==="string","pkg_info json missing registry latest version");assert(typeof pkgInfoJson.versionCount==="number","pkg_info json missing version count");const pkgInfoVerboseJson=assertJsonResult(await callTool(caller,"pkg_info",{target:"npm:express",format:"json",verbose:true}),"pkg_info verbose json");assertRecord(pkgInfoVerboseJson,"pkg_info verbose json");for(const[mode,payload]of[["default",pkgInfoJson],["verbose",pkgInfoVerboseJson]]){const lifecycle=payload.lifecycle;if(lifecycle===undefined)continue;assertRecord(lifecycle,`pkg_info ${mode} lifecycle`);assert(!("checks"in lifecycle),`pkg_info ${mode} JSON leaked internal lifecycle checks`);for(const key of["findings","retainedWarnings"]){if(lifecycle[key]!==undefined)assert(Array.isArray(lifecycle[key])&&lifecycle[key].length>0,`pkg_info ${mode} lifecycle ${key} must be nonempty when present`)}assert([lifecycle.findings,lifecycle.retainedWarnings].some((entries)=>Array.isArray(entries)&&entries.length>0),`pkg_info ${mode} empty lifecycle should be omitted`);if(lifecycle.contentSafety!==undefined){assertRecord(lifecycle.contentSafety,`pkg_info ${mode} lifecycle content safety`);assert(lifecycle.contentSafety.filtered===true,`pkg_info ${mode} lifecycle should omit false filtering flags`)}}assertRecord(pkgInfoJson.downloads,"pkg_info json downloads");assert(typeof pkgInfoJson.downloads.refreshedAt==="string","pkg_info json missing download refresh date");assertRecord(pkgInfoJson.advisoryHistory,"pkg_info json advisory history");assert(typeof pkgInfoJson.advisoryHistory.total==="number","pkg_info json missing advisory history count");assert(!("install"in pkgInfoJson)&&!("usage"in pkgInfoJson),"pkg_info json should not include quickstart fields");const depsText=assertDefaultText(await callTool(caller,"pkg_deps",{target:"npm:express"}),"pkg_deps default");assert(depsText.includes("Runtime dependencies:"),"pkg_deps default missing runtime heading");assert(depsText.includes('pass lifecycle="all"'),"pkg_deps default missing MCP-native lifecycle hint");const depsAllText=assertDefaultText(await callTool(caller,"pkg_deps",{target:"npm:express",lifecycle:"all"}),"pkg_deps lifecycle all");assert(depsAllText.includes("Dependency groups:"),"pkg_deps lifecycle all missing groups heading");assert(!depsAllText.includes("Hidden groups:"),"pkg_deps lifecycle all still hides groups");const depsJson=assertJsonResult(await callTool(caller,"pkg_deps",{target:"npm:express",format:"json"}),"pkg_deps json");assertRecord(depsJson,"pkg_deps json");assertRecord(depsJson.runtime,"pkg_deps json runtime");const depsIssuesText=assertDefaultText(await callTool(caller,"pkg_deps",{target:"npm:express",include_issues:true}),"pkg_deps issues default");assert(depsIssuesText.includes("Dependency issues"),"pkg_deps issues default missing issue heading");const depsIssuesJson=assertJsonResult(await callTool(caller,"pkg_deps",{target:"npm:express",include_issues:true,format:"json"}),"pkg_deps issues json");assertRecord(depsIssuesJson,"pkg_deps issues json");assert(!("transitive"in depsIssuesJson),"pkg_deps issues json should not expose ordinary transitive output");assertRecord(depsIssuesJson.issues,"pkg_deps issues json issues");assertRecord(depsIssuesJson.issues.scope,"pkg_deps issues json scope");assert(depsIssuesJson.issues.scope.mode==="full","pkg_deps issues json should report full scope");for(const category of["deprecated","outdated","duplicates","conflicts"]){assertRecord(depsIssuesJson.issues[category],`pkg_deps issues json ${category}`);assert(typeof depsIssuesJson.issues[category].count==="number",`pkg_deps issues json ${category} missing count`);assert(Array.isArray(depsIssuesJson.issues[category].items),`pkg_deps issues json ${category} missing items`)}const vulnsText=assertDefaultText(await callTool(caller,"pkg_vulns",{target:"npm:express"}),"pkg_vulns default");assert(vulnsText.includes("express")||vulnsText.includes("vulnerab"),"pkg_vulns default missing context");assert(!vulnsText.includes("use -v"),"pkg_vulns leaked CLI -v hint");const transitiveVulnsText=assertDefaultText(await callTool(caller,"pkg_vulns",{target:SMOKE_TRANSITIVE_VULNERABILITY_TARGET,include_transitive:true}),"pkg_vulns transitive default");assertTransitiveVulnerabilityText(transitiveVulnsText,"pkg_vulns transitive default");const transitiveVulnsJson=assertJsonResult(await callTool(caller,"pkg_vulns",{target:SMOKE_TRANSITIVE_VULNERABILITY_TARGET,include_transitive:true,advisory_scope:"all",format:"json"}),"pkg_vulns transitive json");assertTransitiveVulnerabilityJson(transitiveVulnsJson,"pkg_vulns transitive json");assertRecord(transitiveVulnsJson,"pkg_vulns transitive json");assert(transitiveVulnsJson.transitive.advisoryScope==="all","pkg_vulns transitive json did not apply all advisory scope");const filteredVulnsText=assertDefaultText(await callTool(caller,"pkg_vulns",{target:"npm:lodash@4.17.20",min_severity:"high"}),"pkg_vulns filtered default");assert(filteredVulnsText.includes("Filter severity >= high"),"pkg_vulns filtered default missing filter echo");assert(!filteredVulnsText.includes("use -v"),"pkg_vulns filtered default leaked CLI -v hint");const vulnsJson=assertJsonResult(await callTool(caller,"pkg_vulns",{target:"npm:express",format:"json"}),"pkg_vulns json");assertRecord(vulnsJson,"pkg_vulns json");assertRecord(vulnsJson.summary,"vulnerability summary");assert(typeof vulnsJson.summary.assessmentComplete==="boolean","missing assessment completeness");assertRecord(vulnsJson.related,"related vulnerabilities");assert(Array.isArray(vulnsJson.related.advisories),"missing Related advisory rows");assert("summary"in vulnsJson||"advisories"in vulnsJson,"pkg_vulns json missing vulnerability data");const filteredVulnsJson=assertJsonResult(await callTool(caller,"pkg_vulns",{target:"npm:lodash@4.17.20",min_severity:"high",format:"json"}),"pkg_vulns filtered json");assertRecord(filteredVulnsJson,"pkg_vulns filtered json");assertRecord(filteredVulnsJson.filter,"pkg_vulns filtered json filter");assert(filteredVulnsJson.filter.minSeverity==="high","pkg_vulns filtered json missing severity filter echo");const scopedVulnsText=assertDefaultText(await callTool(caller,"pkg_vulns",{target:"npm:express",advisory_scope:"non_affecting"}),"pkg_vulns scoped default");assert(scopedVulnsText.includes("Scope non-affecting advisories only"),"pkg_vulns scoped default missing scope echo");assert(scopedVulnsText.includes("No active vulnerabilities affect this version"),"pkg_vulns scoped default missing current-risk statement");assert(!scopedVulnsText.includes("use -v"),"pkg_vulns scoped default leaked CLI -v hint");const scopedVulnsJson=assertJsonResult(await callTool(caller,"pkg_vulns",{target:"npm:express",advisory_scope:"non_affecting",format:"json"}),"pkg_vulns scoped json");assertRecord(scopedVulnsJson,"pkg_vulns scoped json");assertRecord(scopedVulnsJson.filter,"pkg_vulns scoped json filter");assert(scopedVulnsJson.filter.advisoryScope==="non_affecting","pkg_vulns scoped json missing advisory scope echo");const unknownVulnsText=assertDefaultText(await callTool(caller,"pkg_vulns",{target:"npm:lodash@4.17.20",advisory_scope:"unknown"}),"pkg_vulns unknown scope");assert(unknownVulnsText.includes("Scope unknown"),"pkg_vulns unknown scope missing scope echo");const unknownVulnsJson=assertJsonResult(await callTool(caller,"pkg_vulns",{target:"npm:lodash@4.17.20",advisory_scope:"unknown",format:"json"}),"pkg_vulns unknown json");assertRecord(unknownVulnsJson,"pkg_vulns unknown json");assertRecord(unknownVulnsJson.summary,"pkg_vulns unknown summary");assert(typeof unknownVulnsJson.summary.unknownVulnerabilityCount==="number","pkg_vulns missing unknown count");assert(typeof unknownVulnsJson.summary.assessmentStatus==="string","pkg_vulns missing assessment status in JSON");const transitiveUnknown=assertJsonResult(await callTool(caller,"pkg_vulns",{target:"pypi:torchvision@0.20.1",advisory_scope:"unknown",include_transitive:true,format:"json"}),"pkg_vulns transitive unknown");assertRecord(transitiveUnknown,"pkg_vulns transitive unknown");assertRecord(transitiveUnknown.transitive,"pkg_vulns transitive unknown audit");assertRecord(transitiveUnknown.transitive.summary,"pkg_vulns transitive unknown summary");assert(typeof transitiveUnknown.transitive.summary.unknownCount==="number","pkg_vulns missing transitive unknown count");assert(transitiveUnknown.transitive.advisoryScope==="unknown","pkg_vulns missing transitive unknown scope");assertTransitiveVulnerabilityJson(transitiveUnknown,"pkg_vulns transitive unknown");assert(Array.isArray(transitiveUnknown.transitive.packages),"pkg_vulns missing packages");for(const pkg of transitiveUnknown.transitive.packages){assertRecord(pkg,"pkg_vulns unknown package");assert(Array.isArray(pkg.occurrences),"pkg_vulns missing occurrences");for(const row of pkg.occurrences){assertRecord(row,"pkg_vulns unknown occurrence");assert(row.affectsResolvedVersion===false,"pkg_vulns unknown row claims a match");assert(typeof row.assessmentStatus==="string","pkg_vulns missing occurrence status");assert(Array.isArray(row.assessmentReasons),"pkg_vulns missing occurrence reasons")}}const changelogText=assertToolText(await callTool(caller,"pkg_changelog",{target:"npm:express",limit:1}),"pkg_changelog default");assert(!changelogText.includes("--verbose"),"pkg_changelog default leaked CLI verbose flag");if(changelogText.includes("more lines")||changelogText.includes("full bodies")){assert(changelogText.includes("pass verbatim=true"),"pkg_changelog truncation hint is not MCP-native")}const changelogBodyLinesText=assertDefaultText(await callTool(caller,"pkg_changelog",{target:"npm:express",limit:2,body_lines:3}),"pkg_changelog body_lines");if(changelogBodyLinesText.includes("more lines")||changelogBodyLinesText.includes("full bodies")){assert(changelogBodyLinesText.includes("pass verbatim=true"),"pkg_changelog body_lines missing MCP-native truncation hint")}assert(!changelogBodyLinesText.includes("--verbose"),"pkg_changelog body_lines leaked CLI verbose flag");const changelogFullBodiesText=assertToolText(await callTool(caller,"pkg_changelog",{target:"npm:express",limit:2,body_lines:3,verbatim:true}),"pkg_changelog verbose overrides preview controls");assert(!changelogFullBodiesText.includes("pass verbatim=true"),"pkg_changelog verbose still truncated body previews");const changelogJson=assertJsonResult(await callTool(caller,"pkg_changelog",{target:"npm:express",limit:1,format:"json"}),"pkg_changelog json");assertRecord(changelogJson,"pkg_changelog json");assertRecord(changelogJson.entries,"pkg_changelog json entries");assertRecord(changelogJson.statements,"pkg_changelog json statements");assert(Array.isArray(changelogJson.statements.items),"pkg_changelog json missing parsed statements");assert(Array.isArray(changelogJson.statements.coverage),"pkg_changelog json missing coverage");assert(Array.isArray(changelogJson.entries.items)&&changelogJson.entries.items.every((entry)=>typeof entry==="object"&&entry!==null&&!("body"in entry)),"pkg_changelog default JSON over-fetched note bodies");const filteredChangelog=assertJsonResult(await callTool(caller,"pkg_changelog",{target:"npm:express@5.2.1",changes:"actionable",format:"json"}),"pkg_changelog actionable");assertRecord(filteredChangelog,"pkg_changelog actionable");assertRecord(filteredChangelog.statements,"pkg_changelog filtered statements");assert(Array.isArray(filteredChangelog.statements.items)&&filteredChangelog.statements.items.every((item)=>typeof item==="object"&&item!==null&&("classification"in item)&&typeof item.classification==="object"&&item.classification!==null&&("tier"in item.classification)&&item.classification.tier==="must_act"),"pkg_changelog actionable includes another tier");const timelineChangelog=assertJsonResult(await callTool(caller,"pkg_changelog",{target:"npm:express",limit:1,omit_bodies:true,changes:"ignored",format:"json"}),"pkg_changelog timeline-only");assertRecord(timelineChangelog,"pkg_changelog timeline-only");assert(!("statements"in timelineChangelog),"pkg_changelog timeline-only classified notes");const changelogExact=assertJsonResult(await callTool(caller,"pkg_changelog",{target:"npm:express@5.2.1",format:"json"}),"pkg_changelog exact json");assertRecord(changelogExact,"pkg_changelog exact json");assert(changelogExact.mode==="exact","pkg_changelog exact json mode");const exactEntries=changelogExact.entries;assert(exactEntries?.items?.[0]?.version==="5.2.1","pkg_changelog exact json resolved version");assert(typeof exactEntries?.items?.[0]?.hasChangelog==="boolean","pkg_changelog exact json missing hasChangelog");const changelogRepo=await callTool(caller,"pkg_changelog",{target:"github:expressjs/express",format:"json"});const changelogRepoEnvelope=assertCleanErrorEnvelope(changelogRepo,"pkg_changelog repository target");assert(changelogRepoEnvelope.code==="INVALID_ARGUMENT",`pkg_changelog repository target: expected INVALID_ARGUMENT, got ${changelogRepoEnvelope.code}`);const changelogTimeline=assertDefaultText(await callTool(caller,"pkg_changelog",{target:"npm:express",limit:2,omit_bodies:true}),"pkg_changelog timeline");assert(!changelogTimeline.includes("What's Changed"),"pkg_changelog omit_bodies=true still emitted bodies");const upgradeReviewText=assertToolText(await callTool(caller,"pkg_upgrade_review",{registry:"npm",package_name:"express",current_version:"5.0.0",target_version:"5.2.1",skip_transitive_security:true}),"pkg_upgrade_review default");const upgradeReviewFirstLine=upgradeReviewText.split(`
7
11
  `)[0]?.trim();assert(upgradeReviewFirstLine==="Upgrade review - 1 package","pkg_upgrade_review default missing outcome headline");assert(upgradeReviewText.includes("npm:express 5.0.0 -> 5.2.1")&&upgradeReviewText.includes(`
8
12
  Security
9
13
  `)&&upgradeReviewText.includes(`
10
- Changes (classified by agent)
11
- `),"pkg_upgrade_review default missing grouped evidence");assert(!upgradeReviewText.includes("pkg_upgrade_review")&&!/\b(?:recommendation|risk level|assessment)\b/i.test(upgradeReviewText),"pkg_upgrade_review default leaked assessment language");assert(upgradeReviewText.includes("Classification coverage:")&&upgradeReviewText.includes("labeled no impact")&&upgradeReviewText.includes("Selection: focused"),"pkg_upgrade_review text missing classification coverage or selection");const upgradeReviewJson=assertJsonResult(await callTool(caller,"pkg_upgrade_review",{registry:"npm",package_name:"express",current_version:"5.0.0",target_version:"5.2.1",skip_transitive_security:true,format:"json"}),"pkg_upgrade_review json");assertRecord(upgradeReviewJson,"pkg_upgrade_review json");assertRecord(upgradeReviewJson.summary,"pkg_upgrade_review json summary");assert(Array.isArray(upgradeReviewJson.reviews),"pkg_upgrade_review json missing reviews array");const firstUpgradeReview=upgradeReviewJson.reviews[0];assert(firstUpgradeReview,"pkg_upgrade_review json missing first review");assertRecord(firstUpgradeReview.changelog,"pkg_upgrade_review changelog");assert(!("riskItems"in firstUpgradeReview.changelog),"pkg_upgrade_review returned deprecated riskItems");const upgradeStatements=firstUpgradeReview.changelog.statements;assertRecord(upgradeStatements,"pkg_upgrade_review statements");assert(upgradeStatements.selection==="focused","pkg_upgrade_review statements selection must be focused");assert(Array.isArray(upgradeStatements.items),"pkg_upgrade_review statements missing items array");assert(Array.isArray(upgradeStatements.coverage),"pkg_upgrade_review statements missing coverage array");assert(typeof upgradeStatements.count==="number"&&upgradeStatements.count===upgradeStatements.items.length,"pkg_upgrade_review statements count does not match items");assert(typeof upgradeStatements.totalCount==="number","pkg_upgrade_review statements missing totalCount");assert(typeof upgradeStatements.matchingCount==="number","pkg_upgrade_review statements missing matchingCount");for(const item of upgradeStatements.items){assertRecord(item,"pkg_upgrade_review statement item");assert(typeof item.text==="string","pkg_upgrade_review missing statement text");assert(item.fullText===undefined||typeof item.fullText==="string","pkg_upgrade_review invalid statement fullText");assert(typeof item.sourcePosition==="number","pkg_upgrade_review missing statement sourcePosition");assert(item.url===undefined||typeof item.url==="string","pkg_upgrade_review invalid statement URL");if(item.classification!==null){assertRecord(item.classification,"pkg_upgrade_review classification");assert(typeof item.classification.tier==="string","pkg_upgrade_review missing classification tier");assert(typeof item.classification.ambiguous==="boolean","pkg_upgrade_review missing classification ambiguous flag");assert(typeof item.classification.model==="string","pkg_upgrade_review missing classification model");assert(typeof item.classification.formulation==="string","pkg_upgrade_review missing classification formulation")}}const riskCoverage=firstUpgradeReview.changelog.riskCoverage;assertRecord(riskCoverage,"pkg_upgrade_review riskCoverage");assert(!("itemsOmitted"in riskCoverage),"pkg_upgrade_review returned deprecated itemsOmitted counter");for(const counter of["versionsClassified","versionsNotAssessed","versionsWithoutNotes","versionsUnparseable","unitsNoImpact","itemsMustActConfident","itemsMustActAmbiguous","itemsShouldKnowConfident","itemsShouldKnowAmbiguous","itemsUnclassified"]){assert(typeof riskCoverage[counter]==="number",`pkg_upgrade_review missing coverage counter ${counter}`)}for(const forbidden of["risk","riskLevel","recommendation","findings","verification"]){assert(!(forbidden in firstUpgradeReview),`pkg_upgrade_review json leaked judgment field ${forbidden}`)}const packageListArgs={target:SMOKE_PACKAGE_TARGET,paths:["package.json"],limit:1};const packageListText=assertDefaultText(await callTool(caller,"list",packageListArgs),"list package default");assert(packageListText.includes("package.json"),"list package default missing package.json");const packageListJson=assertJsonResult(await callTool(caller,"list",{...packageListArgs,format:"json"}),"list package json");assertRecord(packageListJson,"list package json");assert(packageListJson.inventoryKind==="SOURCE"&&packageListJson.requestedTarget===SMOKE_PACKAGE_TARGET&&Array.isArray(packageListJson.entries),"list package json missing source inventory identity or entries");const packageEntries=packageListJson.entries;const packageEntry=packageEntries.find((entry)=>typeof entry==="object"&&entry!==null&&entry.path==="package.json");assert(packageEntry,"list package json missing package.json entry");const packageRead=packageEntry.read;assertRecord(packageRead,"list package json read action");const packageReadTarget=packageRead.target;const packageReadPath=packageRead.path;assert(typeof packageReadTarget==="string"&&typeof packageReadPath==="string","list package json entry missing read target or path");assert(typeof packageListJson.hasMore==="boolean"&&packageListJson.hasMore===(typeof packageListJson.nextCursor==="string"&&packageListJson.nextCursor.length>0)&&(packageListJson.hasMore||packageListJson.nextCursor===null),"list package json hasMore/nextCursor mismatch");const rootListArgs={target:SMOKE_PACKAGE_TARGET,limit:1};const firstRootPage=assertDefaultText(await callTool(caller,"list",rootListArgs),"list package root first page text");const firstRootPath=listTextFirstPath(firstRootPage,"list package root first page text");const nextCursor=listTextContinuation(firstRootPage,"list package root first page text");assert(firstRootPage.includes("More results: repeat this list, adding:")&&firstRootPath.length>0&&nextCursor.length>0,"list package root first page must expose one path and a text continuation");const secondRootPage=assertDefaultText(await callTool(caller,"list",{...rootListArgs,after:nextCursor}),"list package root continuation text");const secondRootPath=listTextFirstPath(secondRootPage,"list package root continuation text");assert(secondRootPath.length>0&&secondRootPath!==firstRootPath,"list package root continuation repeated its first entry");const packageReadText=assertDefaultText(await callTool(caller,"read",{target:packageReadTarget,path:packageReadPath,start_line:1,end_line:5}),"read package list action default");assert(/^1\s+/m.test(packageReadText),"read package list action default missing line numbers");const packageReadJson=assertJsonResult(await callTool(caller,"read",{target:packageReadTarget,path:packageReadPath,start_line:1,end_line:5,format:"json"}),"read package list action json");assertRecord(packageReadJson,"read package list action json");assert(packageReadJson.path===packageReadPath,"read package list action json path mismatch");const siteListArgs={target:"site:expressjs.com",paths:["/en/resources/"],limit:20};const siteListText=assertDefaultText(await callTool(caller,"list",siteListArgs),"list site default");assert(siteListText.includes('Read pages: read target="site:expressjs.com" path=$path')&&siteListText.includes("en/resources/"),"list site default missing follow-up header or resources path");const siteListJson=assertJsonResult(await callTool(caller,"list",{...siteListArgs,format:"json"}),"list site json");assertRecord(siteListJson,"list site json");assert(siteListJson.inventoryKind==="SITE"&&siteListJson.requestedTarget===siteListArgs.target&&Array.isArray(siteListJson.entries),"list site json missing site inventory identity or entries");const siteEntries=siteListJson.entries;const sitePage=siteEntries.find((entry)=>typeof entry==="object"&&entry!==null&&entry.kind==="PAGE");assert(sitePage,"list site json missing PAGE entry");const siteRead=sitePage.read;assertRecord(siteRead,"list site json PAGE read action");const siteReadTarget=siteRead.target;const siteReadPath=siteRead.path;assert(typeof siteReadTarget==="string"&&typeof siteReadPath==="string","list site json PAGE missing read target or path");for(const[format,label]of[[undefined,"default"],["json","json"]]){const result=await callTool(caller,"read",{target:siteReadTarget,path:siteReadPath,start_line:1,end_line:5,...format?{format}:{}});if(format){const value=assertJsonResult(result,`read site list action ${label}`);assertRecord(value,`read site list action ${label}`);assert(typeof value.content==="string"&&value.startLine===1&&typeof value.endLine==="number"&&value.endLine>=1&&value.endLine<=5&&typeof value.totalLines==="number"&&value.totalLines>=value.endLine,`read site list action ${label} missing content or backend range`)}else{const text=assertDefaultText(result,`read site list action ${label}`);assert(text.length>0,`read site list action ${label} missing content`)}}const directUrlReadText=assertDefaultText(await callTool(caller,"read",{target:"https://expressjs.com/en/resources/",start_line:1,end_line:5}),"read exact site URL default");assert(directUrlReadText.length>0,"read exact site URL default missing content");const directUrlReadJson=assertJsonResult(await callTool(caller,"read",{target:"https://expressjs.com/en/resources/",start_line:1,end_line:5,format:"json"}),"read exact site URL json");assertRecord(directUrlReadJson,"read exact site URL json");assert(typeof directUrlReadJson.content==="string"&&directUrlReadJson.startLine===1&&typeof directUrlReadJson.endLine==="number"&&directUrlReadJson.endLine>=1&&directUrlReadJson.endLine<=5&&typeof directUrlReadJson.totalLines==="number"&&directUrlReadJson.totalLines>=directUrlReadJson.endLine,"read exact site URL json missing content or backend range");assertErrorCode(await callTool(caller,"read",{target:"https://docs.example.invalid/githits-smoke-unknown",format:"json"}),"read unknown URL","NOT_FOUND");const grepArgs={targets:[{target:SMOKE_PACKAGE_TARGET}],pattern:"router",max_matches:2,wait_timeout_ms:60000};const grepText=assertDefaultText(await callTool(caller,"grep",grepArgs),"grep default");const grepJson=assertGrepResult(assertJsonResult(await callTool(caller,"grep",{...grepArgs,format:"json"}),"grep json"),"grep json");assert(grepJson.traversal==="RESUMABLE_LIMIT"&&typeof grepJson.nextCursor==="string","grep first page must expose resumable coverage and a cursor");const grepHits=grepJson.hits;const repositoryHit=grepHits.find((hit)=>hit.__typename==="GrepRepositoryHit");const hostedDocsHit=grepHits.find((hit)=>hit.__typename==="GrepSiteHit");assert(repositoryHit,"grep json missing repository source evidence");assert(hostedDocsHit,"grep json missing hosted documentation evidence");const grepScopes=grepJson.targets;for(const kind of["REPOSITORY","SITE"]){const scope=grepScopes.find((target)=>target.kind===kind);assert(scope,`grep json missing ${kind.toLowerCase()} scope status`);assert(scope.requestedInputIndices.includes(0)&&typeof scope.readiness==="string"&&typeof scope.traversal==="string",`grep json ${kind.toLowerCase()} scope is missing input or readiness status`)}assert(grepText.includes("Sources:")&&grepText.includes("Files: read target=$target path=$path")&&grepText.includes("Pages: read target=$url")&&grepText.includes("More results:")&&grepText.includes(`cursor=${JSON.stringify(grepJson.nextCursor)}`),"grep default missing mixed-source, exact-read, or continuation guidance");const grepCursor=grepJson.nextCursor;const grepSecondPage=assertGrepResult(assertJsonResult(await callTool(caller,"grep",{...grepArgs,cursor:grepCursor,format:"json"}),"grep continuation json"),"grep continuation json");assert(grepSecondPage.hits.length>0&&grepSecondPage.targets.length>0,"grep continuation must return page evidence and target readiness");assert(grepSecondPage.targets.every((target)=>target.requestedInputIndices.includes(0)&&typeof target.readiness==="string"),"grep continuation lost input attribution or target readiness");const repositoryReadArgs=grepReadArgs(repositoryHit,"json");const repositoryReadJson=assertJsonResult(await callTool(caller,"read",repositoryReadArgs),"read grep repository action json");assertRecord(repositoryReadJson,"read grep repository action json");const repositoryAction=repositoryHit.read;assert(repositoryReadJson.path===repositoryAction.path&&repositoryReadJson.startLine===repositoryAction.startLine&&repositoryReadJson.endLine===repositoryAction.endLine,"read grep repository action changed its path or line range");const repositoryReadText=assertDefaultText(await callTool(caller,"read",grepReadArgs(repositoryHit)),"read grep repository action text");assert(repositoryReadText.includes(`${repositoryAction.startLine} `),"read grep repository action text omitted the returned line");const hostedReadArgs=grepReadArgs(hostedDocsHit,"json");const hostedReadJson=assertJsonResult(await callTool(caller,"read",hostedReadArgs),"read grep hosted documentation action json");assertRecord(hostedReadJson,"read grep hosted documentation action json");const hostedAction=hostedDocsHit.read;assert(hostedReadJson.docsReadTarget===hostedAction.target&&hostedReadJson.startLine===hostedAction.startLine&&hostedReadJson.endLine===hostedAction.endLine,"read grep hosted documentation action changed its page or line range");const hostedReadText=assertDefaultText(await callTool(caller,"read",grepReadArgs(hostedDocsHit)),"read grep hosted documentation action text");assert(typeof hostedReadJson.content==="string"&&hostedReadJson.content.length>0&&hostedReadText.includes(hostedReadJson.content),"read grep hosted documentation action text omitted the returned content");const inlineSearchJson=assertJsonResult(await callTool(caller,"search",{target:SMOKE_PACKAGE_TARGET,query:INLINE_SEARCH_QUERY,source:"code",limit:1,format:"json"}),"search inline qualifiers");assertInlineSearchSuccess(inlineSearchJson,INLINE_SEARCH_QUERY,"search inline qualifiers");for(const[qualifier,source]of[["kind:bogus","symbol"],["category:bogus","symbol"],["intent:bogus","code"]]){assertInlineSearchError(await callTool(caller,"search",{target:SMOKE_PACKAGE_TARGET,query:`router ${qualifier}`,source,format:"json"}),`search invalid inline qualifier ${qualifier}`)}const searchText=assertDefaultText(await callTool(caller,"search",{target:SMOKE_PACKAGE_TARGET,query:"router",limit:1}),"search default");assertSearchDefaultText(searchText,"search default");const searchJson=assertJsonResult(await callTool(caller,"search",{target:SMOKE_PACKAGE_TARGET,query:"router",limit:1,format:"json"}),"search json");assertRecord(searchJson,"search json");let docsSearchJson=assertJsonResult(await callTool(caller,"search",{target:"site:expressjs.com",query:"routing",source:"docs",limit:10,wait_timeout_ms:60000,format:"json"}),"documentation search json");assertRecord(docsSearchJson,"documentation search json");if(docsSearchJson.completed!==true&&typeof docsSearchJson.searchRef==="string"){docsSearchJson=assertJsonResult(await callTool(caller,"search_status",{search_ref:docsSearchJson.searchRef,wait_timeout_ms:60000,format:"json"}),"documentation search status json");assertRecord(docsSearchJson,"documentation search status json")}const docsSearchEvidence=typeof docsSearchJson.result==="object"&&docsSearchJson.result!==null?docsSearchJson.result:docsSearchJson;assertRecord(docsSearchEvidence,"documentation search evidence");assert(Array.isArray(docsSearchEvidence.results),"documentation search json missing results");const hostedDocumentationHits=docsSearchEvidence.results.filter((entry)=>{if(typeof entry!=="object"||entry===null)return false;const hit=entry;if(hit.type!=="documentation_page")return false;const locator=hit.locator;return typeof locator==="object"&&locator!==null&&typeof locator.docsReadTarget==="string"&&/^https?:\/\//i.test(locator.docsReadTarget)});assert(hostedDocumentationHits.length>0,"documentation search json missing hosted documentation_page evidence");for(const hit of hostedDocumentationHits){assert(typeof hit.followUp==="string"&&!/\b(?:start_line|end_line)=/.test(hit.followUp),"hosted documentation follow-up replayed search line bounds")}const searchRef=typeof searchJson.searchRef==="string"?searchJson.searchRef:undefined;if(searchRef){const statusJson=assertJsonResult(await callTool(caller,"search_status",{search_ref:searchRef,wait_timeout_ms:0,format:"json"}),"search_status json");assertRecord(statusJson,"search_status json");assert("completed"in statusJson||"progress"in statusJson,"search_status json missing status data")}else{assertErrorCode(await callTool(caller,"search_status",{search_ref:"smoke-invalid-search-ref",wait_timeout_ms:0,format:"json"}),"search_status invalid ref","NOT_FOUND")}assertErrorCode(await callTool(caller,"research",{target:"npm:express",thread_id:"018f47a6-7b32-7b1e-8f45-6a2d39c81720",question:"How is routing dispatched?",format:"json"}),"research target and thread_id","INVALID_ARGUMENT")}async function runResolveSmoke(caller){const text=assertDefaultText(await callTool(caller,"resolve_target",{name:"express"}),"resolve_target default");assertMcpResolveText(text);for(const expected of["Targets:","npm:express","github:expressjs/express","site:expressjs.com","Related targets:"]){assert(text.includes(expected),`express resolution missing ${expected}`)}const fuzzyArgs={name:"lodahs",preferred_kind:"package"};const fuzzyText=assertDefaultText(await callTool(caller,"resolve_target",fuzzyArgs),"resolve_target fuzzy default");assert(!fuzzyText.includes("name similarity")&&!fuzzyText.includes("coarse lexical support")&&fuzzyText.includes("indexed package snapshot")&&!fuzzyText.includes("readiness")&&!fuzzyText.includes("no code")&&!fuzzyText.includes("no docs"),"fuzzy resolve default text should omit lexical and negative availability detail");const verbose=assertDefaultText(await callTool(caller,"resolve_target",{...fuzzyArgs,verbose:true}),"resolve_target fuzzy verbose");assert(/\d+% name similarity/.test(verbose)&&verbose.includes("Name similarity is coarse lexical support; candidate order follows broader backend policy."),"fuzzy resolve verbose text should qualify lexical evidence");const json=assertJsonResult(await callTool(caller,"resolve_target",{name:"express",format:"json"}),"resolve_target json");assertRecord(json,"resolve_target json");assert(Array.isArray(json.candidates),"resolve_target json missing candidates");const best=json.candidates.find((candidate)=>{assertRecord(candidate,"resolve candidate");return candidate.target==="npm:express"});assertRecord(best,"resolve express candidate");assert(typeof best.latestVersionMaliciousStatus==="string"&&typeof json.targetsTruncated==="boolean","resolve_target json missing security status or truncation");assert(json.best==="npm:express"&&json.ambiguous===false&&(best.confidence==="exact"||best.confidence==="high")&&(best.latestVersionMaliciousStatus==="clear"||best.latestVersionMaliciousStatus==="not_applicable"),"express resolution must provide an unambiguous actionable best before the follow-up");const inventory=assertJsonResult(await callTool(caller,"list",{target:json.best,depth:1,limit:2,format:"json"}),"resolve_target selected-target inventory");assertRecord(inventory,"resolve_target selected-target inventory");assert(Array.isArray(inventory.entries),"resolved target inventory missing entries");const fuzzyJson=assertJsonResult(await callTool(caller,"resolve_target",{...fuzzyArgs,format:"json"}),"resolve_target fuzzy json");assertRecord(fuzzyJson,"resolve_target fuzzy json");assert(Array.isArray(fuzzyJson.candidates)&&fuzzyJson.candidates.some((candidate)=>{assertRecord(candidate,"fuzzy resolve candidate");return candidate.target==="npm:lodash"&&typeof candidate.nameSimilarity==="number"}),"fuzzy resolve json should preserve numeric name similarity for npm:lodash")}async function runMcpSmoke(caller,options={}){const logger=options.logger??console;const includeLiveTools=options.includeLiveTools??true;const toolsResponse=await caller.listTools();const toolNames=new Set(toolsResponse.tools.map((tool)=>tool.name));assert(!toolNames.has("feedback"),"listTools advertises removed feedback tool");assert(!toolNames.has("code_grep"),"listTools advertises retired code_grep instead of grep");for(const expected of EXPECTED_MCP_TOOLS){assert(toolNames.has(expected),`listTools missing ${expected}`)}for(const tool of toolsResponse.tools){const expectedReadOnlyHint=tool.name!=="get_example"&&tool.name!=="research";assert(tool.annotations?.readOnlyHint===expectedReadOnlyHint,`${tool.name} must advertise readOnlyHint: ${expectedReadOnlyHint}`);assert(tool.annotations?.idempotentHint===expectedReadOnlyHint,`${tool.name} must advertise idempotentHint: ${expectedReadOnlyHint}`);const expectedOpenWorldHint=tool.name!=="quick_start";assert(tool.annotations?.openWorldHint===expectedOpenWorldHint,`${tool.name} must advertise openWorldHint: ${expectedOpenWorldHint}, got ${String(tool.annotations?.openWorldHint)}`);assert(tool.annotations?.destructiveHint===false,`${tool.name} must advertise destructiveHint: false`)}const quickStart=assertDefaultText(await callTool(caller,"quick_start",{}),"quick_start default");for(const expected of["## Choose a tool","`search`","`list`","`grep`","`read`","`code_diff`","`resolve_target`","`research`"]){assert(quickStart.includes(expected),`quick_start default missing ${expected}`)}assert(!quickStart.includes("code_grep"),"quick_start still routes matching to retired code_grep");if(!includeLiveTools)return;if(await assertLiveOrAuthRequired(caller,logger)){await runLiveSmoke(caller);logger.log("MCP smoke passed")}}export{EXPECTED_MCP_TOOLS,assertCleanErrorEnvelope,assertDefaultText,assertHttpUnauthorizedChallenge,assertJsonResult,assertMcpResolveText,callToolText,isResolveDirectTargetUnwarned,resultText,runMcpSmoke};
14
+ Changelog statements
15
+ `),"pkg_upgrade_review default missing grouped evidence");assert(!upgradeReviewText.includes("pkg_upgrade_review")&&!/\b(?:recommendation|risk level|assessment)\b/i.test(upgradeReviewText),"pkg_upgrade_review default leaked assessment language");assert(upgradeReviewText.includes("Classification coverage:")&&upgradeReviewText.includes("labeled no impact")&&upgradeReviewText.includes("Selection: focused"),"pkg_upgrade_review text missing classification coverage or selection");const upgradeReviewJson=assertJsonResult(await callTool(caller,"pkg_upgrade_review",{registry:"npm",package_name:"express",current_version:"5.0.0",target_version:"5.2.1",skip_transitive_security:true,format:"json"}),"pkg_upgrade_review json");assertRecord(upgradeReviewJson,"pkg_upgrade_review json");assertRecord(upgradeReviewJson.summary,"pkg_upgrade_review json summary");assert(Array.isArray(upgradeReviewJson.reviews),"pkg_upgrade_review json missing reviews array");const firstUpgradeReview=upgradeReviewJson.reviews[0];assert(firstUpgradeReview,"pkg_upgrade_review json missing first review");assertRecord(firstUpgradeReview.changelog,"pkg_upgrade_review changelog");assert(!("riskItems"in firstUpgradeReview.changelog),"pkg_upgrade_review returned deprecated riskItems");const upgradeStatements=firstUpgradeReview.changelog.statements;assertRecord(upgradeStatements,"pkg_upgrade_review statements");assert(upgradeStatements.selection==="focused","pkg_upgrade_review statements selection must be focused");assert(Array.isArray(upgradeStatements.items),"pkg_upgrade_review statements missing items array");assert(Array.isArray(upgradeStatements.coverage),"pkg_upgrade_review statements missing coverage array");assert(typeof upgradeStatements.count==="number"&&upgradeStatements.count===upgradeStatements.items.length,"pkg_upgrade_review statements count does not match items");assert(typeof upgradeStatements.totalCount==="number","pkg_upgrade_review statements missing totalCount");assert(typeof upgradeStatements.matchingCount==="number","pkg_upgrade_review statements missing matchingCount");for(const item of upgradeStatements.items){assertRecord(item,"pkg_upgrade_review statement item");assert(typeof item.text==="string","pkg_upgrade_review missing statement text");assert(item.fullText===undefined||typeof item.fullText==="string","pkg_upgrade_review invalid statement fullText");assert(typeof item.sourcePosition==="number","pkg_upgrade_review missing statement sourcePosition");assert(item.url===undefined||typeof item.url==="string","pkg_upgrade_review invalid statement URL");if(item.classification!==null){assertRecord(item.classification,"pkg_upgrade_review classification");assert(typeof item.classification.tier==="string","pkg_upgrade_review missing classification tier");assert(typeof item.classification.ambiguous==="boolean","pkg_upgrade_review missing classification ambiguous flag");assert(typeof item.classification.model==="string","pkg_upgrade_review missing classification model");assert(typeof item.classification.formulation==="string","pkg_upgrade_review missing classification formulation")}}const riskCoverage=firstUpgradeReview.changelog.riskCoverage;assertRecord(riskCoverage,"pkg_upgrade_review riskCoverage");assert(!("itemsOmitted"in riskCoverage),"pkg_upgrade_review returned deprecated itemsOmitted counter");for(const counter of["versionsClassified","versionsNotAssessed","versionsWithoutNotes","versionsUnparseable","unitsNoImpact","itemsMustActConfident","itemsMustActAmbiguous","itemsShouldKnowConfident","itemsShouldKnowAmbiguous","itemsUnclassified"]){assert(typeof riskCoverage[counter]==="number",`pkg_upgrade_review missing coverage counter ${counter}`)}for(const forbidden of["risk","riskLevel","recommendation","findings","verification"]){assert(!(forbidden in firstUpgradeReview),`pkg_upgrade_review json leaked judgment field ${forbidden}`)}const packageListArgs={target:SMOKE_PACKAGE_TARGET,paths:["package.json"],limit:1};const packageListText=assertDefaultText(await callTool(caller,"list",packageListArgs),"list package default");assert(packageListText.includes("package.json"),"list package default missing package.json");const packageListJson=assertJsonResult(await callTool(caller,"list",{...packageListArgs,format:"json"}),"list package json");assertRecord(packageListJson,"list package json");assert(packageListJson.inventoryKind==="SOURCE"&&packageListJson.requestedTarget===SMOKE_PACKAGE_TARGET&&Array.isArray(packageListJson.entries),"list package json missing source inventory identity or entries");const packageEntries=packageListJson.entries;const packageEntry=packageEntries.find((entry)=>typeof entry==="object"&&entry!==null&&entry.path==="package.json");assert(packageEntry,"list package json missing package.json entry");const packageRead=packageEntry.read;assertRecord(packageRead,"list package json read action");const packageReadTarget=packageRead.target;const packageReadPath=packageRead.path;assert(typeof packageReadTarget==="string"&&typeof packageReadPath==="string","list package json entry missing read target or path");assert(typeof packageListJson.hasMore==="boolean"&&packageListJson.hasMore===(typeof packageListJson.nextCursor==="string"&&packageListJson.nextCursor.length>0)&&(packageListJson.hasMore||packageListJson.nextCursor===null),"list package json hasMore/nextCursor mismatch");const rootListArgs={target:SMOKE_PACKAGE_TARGET,limit:1};const firstRootPage=assertDefaultText(await callTool(caller,"list",rootListArgs),"list package root first page text");const firstRootPath=listTextFirstPath(firstRootPage,"list package root first page text");const nextCursor=listTextContinuation(firstRootPage,"list package root first page text");assert(firstRootPage.split(`
16
+ `).includes("More results:")&&firstRootPath.length>0&&nextCursor.length>0,"list package root first page must expose one path and a text continuation");const secondRootPage=assertDefaultText(await callTool(caller,"list",{...rootListArgs,after:nextCursor}),"list package root continuation text");const secondRootPath=listTextFirstPath(secondRootPage,"list package root continuation text");assert(secondRootPath.length>0&&secondRootPath!==firstRootPath,"list package root continuation repeated its first entry");const packageReadText=assertDefaultText(await callTool(caller,"read",{target:packageReadTarget,path:packageReadPath,start_line:1,end_line:5}),"read package list action default");assert(/^1\s+/m.test(packageReadText),"read package list action default missing line numbers");const packageReadJson=assertJsonResult(await callTool(caller,"read",{target:packageReadTarget,path:packageReadPath,start_line:1,end_line:5,format:"json"}),"read package list action json");assertRecord(packageReadJson,"read package list action json");assert(packageReadJson.path===packageReadPath,"read package list action json path mismatch");const siteListArgs={target:"site:expressjs.com",paths:["/en/resources/"],limit:20};const siteListText=assertDefaultText(await callTool(caller,"list",siteListArgs),"list site default");assert(siteListText.includes('Read pages: read target="site:expressjs.com" path=$path')&&siteListText.includes("en/resources/"),"list site default missing follow-up header or resources path");const siteListJson=assertJsonResult(await callTool(caller,"list",{...siteListArgs,format:"json"}),"list site json");assertRecord(siteListJson,"list site json");assert(siteListJson.inventoryKind==="SITE"&&siteListJson.requestedTarget===siteListArgs.target&&Array.isArray(siteListJson.entries),"list site json missing site inventory identity or entries");const siteEntries=siteListJson.entries;const sitePage=siteEntries.find((entry)=>typeof entry==="object"&&entry!==null&&entry.kind==="PAGE");assert(sitePage,"list site json missing PAGE entry");const siteRead=sitePage.read;assertRecord(siteRead,"list site json PAGE read action");const siteReadTarget=siteRead.target;const siteReadPath=siteRead.path;assert(typeof siteReadTarget==="string"&&typeof siteReadPath==="string","list site json PAGE missing read target or path");for(const[format,label]of[[undefined,"default"],["json","json"]]){const result=await callTool(caller,"read",{target:siteReadTarget,path:siteReadPath,start_line:1,end_line:5,...format?{format}:{}});if(format){const value=assertJsonResult(result,`read site list action ${label}`);assertRecord(value,`read site list action ${label}`);assert(typeof value.content==="string"&&value.startLine===1&&typeof value.endLine==="number"&&value.endLine>=1&&value.endLine<=5&&typeof value.totalLines==="number"&&value.totalLines>=value.endLine,`read site list action ${label} missing content or backend range`)}else{const text=assertDefaultText(result,`read site list action ${label}`);assert(text.length>0,`read site list action ${label} missing content`)}}const directUrlReadText=assertDefaultText(await callTool(caller,"read",{target:"https://expressjs.com/en/resources/",start_line:1,end_line:5}),"read exact site URL default");assert(directUrlReadText.length>0,"read exact site URL default missing content");const directUrlReadJson=assertJsonResult(await callTool(caller,"read",{target:"https://expressjs.com/en/resources/",start_line:1,end_line:5,format:"json"}),"read exact site URL json");assertRecord(directUrlReadJson,"read exact site URL json");assert(typeof directUrlReadJson.content==="string"&&directUrlReadJson.startLine===1&&typeof directUrlReadJson.endLine==="number"&&directUrlReadJson.endLine>=1&&directUrlReadJson.endLine<=5&&typeof directUrlReadJson.totalLines==="number"&&directUrlReadJson.totalLines>=directUrlReadJson.endLine,"read exact site URL json missing content or backend range");assertErrorCode(await callTool(caller,"read",{target:"https://docs.example.invalid/githits-smoke-unknown",format:"json"}),"read unknown URL","NOT_FOUND");const grepArgs={targets:[{target:SMOKE_PACKAGE_TARGET}],pattern:"router",max_matches:2,wait_timeout_ms:60000};const grepText=assertDefaultText(await callTool(caller,"grep",grepArgs),"grep default");const grepJson=assertGrepResult(assertJsonResult(await callTool(caller,"grep",{...grepArgs,format:"json"}),"grep json"),"grep json");assert(grepJson.traversal==="RESUMABLE_LIMIT"&&typeof grepJson.nextCursor==="string","grep first page must expose resumable coverage and a cursor");const grepHits=grepJson.hits;const repositoryHit=grepHits.find((hit)=>hit.__typename==="GrepRepositoryHit");const hostedDocsHit=grepHits.find((hit)=>hit.__typename==="GrepSiteHit");assert(repositoryHit,"grep json missing repository source evidence");assert(hostedDocsHit,"grep json missing hosted documentation evidence");const grepScopes=grepJson.targets;for(const kind of["REPOSITORY","SITE"]){const scope=grepScopes.find((target)=>target.kind===kind);assert(scope,`grep json missing ${kind.toLowerCase()} scope status`);assert(scope.requestedInputIndices.includes(0)&&typeof scope.readiness==="string"&&typeof scope.traversal==="string",`grep json ${kind.toLowerCase()} scope is missing input or readiness status`)}assert(grepText.includes("Sources:")&&grepText.includes("Files: read target=$target path=$path")&&grepText.includes("Pages: read target=$url")&&grepText.includes("More results:")&&grepText.includes(`cursor=${JSON.stringify(grepJson.nextCursor)}`),"grep default missing mixed-source, exact-read, or continuation guidance");const grepCursor=grepJson.nextCursor;const grepSecondPage=assertGrepResult(assertJsonResult(await callTool(caller,"grep",{...grepArgs,cursor:grepCursor,format:"json"}),"grep continuation json"),"grep continuation json");assert(grepSecondPage.hits.length>0&&grepSecondPage.targets.length>0,"grep continuation must return page evidence and target readiness");assert(grepSecondPage.targets.every((target)=>target.requestedInputIndices.includes(0)&&typeof target.readiness==="string"),"grep continuation lost input attribution or target readiness");const repositoryReadArgs=grepReadArgs(repositoryHit,"json");const repositoryReadJson=assertJsonResult(await callTool(caller,"read",repositoryReadArgs),"read grep repository action json");assertRecord(repositoryReadJson,"read grep repository action json");const repositoryAction=repositoryHit.read;assert(repositoryReadJson.path===repositoryAction.path&&repositoryReadJson.startLine===repositoryAction.startLine&&repositoryReadJson.endLine===repositoryAction.endLine,"read grep repository action changed its path or line range");const repositoryReadText=assertDefaultText(await callTool(caller,"read",grepReadArgs(repositoryHit)),"read grep repository action text");assert(repositoryReadText.includes(`${repositoryAction.startLine} `),"read grep repository action text omitted the returned line");const hostedReadArgs=grepReadArgs(hostedDocsHit,"json");const hostedReadJson=assertJsonResult(await callTool(caller,"read",hostedReadArgs),"read grep hosted documentation action json");assertRecord(hostedReadJson,"read grep hosted documentation action json");const hostedAction=hostedDocsHit.read;assert(hostedReadJson.docsReadTarget===hostedAction.target&&hostedReadJson.startLine===hostedAction.startLine&&hostedReadJson.endLine===hostedAction.endLine,"read grep hosted documentation action changed its page or line range");const hostedReadText=assertDefaultText(await callTool(caller,"read",grepReadArgs(hostedDocsHit)),"read grep hosted documentation action text");assert(typeof hostedReadJson.content==="string"&&hostedReadJson.content.length>0&&hostedReadText.includes(hostedReadJson.content),"read grep hosted documentation action text omitted the returned content");const inlineSearchJson=assertJsonResult(await callTool(caller,"search",{target:SMOKE_PACKAGE_TARGET,query:INLINE_SEARCH_QUERY,source:"code",limit:1,format:"json"}),"search inline qualifiers");assertInlineSearchSuccess(inlineSearchJson,INLINE_SEARCH_QUERY,"search inline qualifiers");for(const[qualifier,source]of[["kind:bogus","symbol"],["category:bogus","symbol"],["intent:bogus","code"]]){assertInlineSearchError(await callTool(caller,"search",{target:SMOKE_PACKAGE_TARGET,query:`router ${qualifier}`,source,format:"json"}),`search invalid inline qualifier ${qualifier}`)}const searchText=assertDefaultText(await callTool(caller,"search",{target:SMOKE_PACKAGE_TARGET,query:"router",limit:1}),"search default");assertSearchDefaultText(searchText,"search default");const searchJson=assertJsonResult(await callTool(caller,"search",{target:SMOKE_PACKAGE_TARGET,query:"router",limit:1,format:"json"}),"search json");assertRecord(searchJson,"search json");let docsSearchJson=assertJsonResult(await callTool(caller,"search",{target:"site:expressjs.com",query:"routing",source:"docs",limit:10,wait_timeout_ms:60000,format:"json"}),"documentation search json");assertRecord(docsSearchJson,"documentation search json");if(docsSearchJson.completed!==true&&typeof docsSearchJson.searchRef==="string"){docsSearchJson=assertJsonResult(await callTool(caller,"search_status",{search_ref:docsSearchJson.searchRef,wait_timeout_ms:60000,format:"json"}),"documentation search status json");assertRecord(docsSearchJson,"documentation search status json")}const docsSearchEvidence=typeof docsSearchJson.result==="object"&&docsSearchJson.result!==null?docsSearchJson.result:docsSearchJson;assertRecord(docsSearchEvidence,"documentation search evidence");assert(Array.isArray(docsSearchEvidence.results),"documentation search json missing results");const hostedDocumentationHits=docsSearchEvidence.results.filter((entry)=>{if(typeof entry!=="object"||entry===null)return false;const hit=entry;if(hit.type!=="documentation_page")return false;const locator=hit.locator;return typeof locator==="object"&&locator!==null&&typeof locator.docsReadTarget==="string"&&/^https?:\/\//i.test(locator.docsReadTarget)});assert(hostedDocumentationHits.length>0,"documentation search json missing hosted documentation_page evidence");for(const hit of hostedDocumentationHits){assert(typeof hit.followUp==="string"&&!/\b(?:start_line|end_line)=/.test(hit.followUp),"hosted documentation follow-up replayed search line bounds")}const searchRef=typeof searchJson.searchRef==="string"?searchJson.searchRef:undefined;if(searchRef){const statusJson=assertJsonResult(await callTool(caller,"search_status",{search_ref:searchRef,wait_timeout_ms:0,format:"json"}),"search_status json");assertRecord(statusJson,"search_status json");assert("completed"in statusJson||"progress"in statusJson,"search_status json missing status data")}else{assertErrorCode(await callTool(caller,"search_status",{search_ref:"smoke-invalid-search-ref",wait_timeout_ms:0,format:"json"}),"search_status invalid ref","NOT_FOUND")}assertErrorCode(await callTool(caller,"research",{target:"npm:express",thread_id:"018f47a6-7b32-7b1e-8f45-6a2d39c81720",question:"How is routing dispatched?",format:"json"}),"research target and thread_id","INVALID_ARGUMENT")}async function runResolveSmoke(caller){const text=assertDefaultText(await callTool(caller,"resolve_target",{name:"express"}),"resolve_target default");assertMcpResolveText(text);for(const expected of["Targets:","npm:express","github:expressjs/express","site:expressjs.com","Related targets:"]){assert(text.includes(expected),`express resolution missing ${expected}`)}const fuzzyArgs={name:"lodahs",preferred_kind:"package"};const fuzzyText=assertDefaultText(await callTool(caller,"resolve_target",fuzzyArgs),"resolve_target fuzzy default");assert(!fuzzyText.includes("name similarity")&&!fuzzyText.includes("coarse lexical support")&&fuzzyText.includes("indexed package snapshot")&&!fuzzyText.includes("readiness")&&!fuzzyText.includes("no code")&&!fuzzyText.includes("no docs"),"fuzzy resolve default text should omit lexical and negative availability detail");const verbose=assertDefaultText(await callTool(caller,"resolve_target",{...fuzzyArgs,verbose:true}),"resolve_target fuzzy verbose");assert(/\d+% name similarity/.test(verbose)&&verbose.includes("Name similarity is coarse lexical support; candidate order follows broader backend policy."),"fuzzy resolve verbose text should qualify lexical evidence");const json=assertJsonResult(await callTool(caller,"resolve_target",{name:"express",format:"json"}),"resolve_target json");assertRecord(json,"resolve_target json");assert(Array.isArray(json.candidates),"resolve_target json missing candidates");const best=json.candidates.find((candidate)=>{assertRecord(candidate,"resolve candidate");return candidate.target==="npm:express"});assertRecord(best,"resolve express candidate");assert(typeof best.latestVersionMaliciousStatus==="string"&&typeof json.targetsTruncated==="boolean","resolve_target json missing security status or truncation");assert(json.best==="npm:express"&&json.ambiguous===false&&(best.confidence==="exact"||best.confidence==="high")&&(best.latestVersionMaliciousStatus==="clear"||best.latestVersionMaliciousStatus==="not_applicable"),"express resolution must provide an unambiguous actionable best before the follow-up");const inventory=assertJsonResult(await callTool(caller,"list",{target:json.best,depth:1,limit:2,format:"json"}),"resolve_target selected-target inventory");assertRecord(inventory,"resolve_target selected-target inventory");assert(Array.isArray(inventory.entries),"resolved target inventory missing entries");const fuzzyJson=assertJsonResult(await callTool(caller,"resolve_target",{...fuzzyArgs,format:"json"}),"resolve_target fuzzy json");assertRecord(fuzzyJson,"resolve_target fuzzy json");assert(Array.isArray(fuzzyJson.candidates)&&fuzzyJson.candidates.some((candidate)=>{assertRecord(candidate,"fuzzy resolve candidate");return candidate.target==="npm:lodash"&&typeof candidate.nameSimilarity==="number"}),"fuzzy resolve json should preserve numeric name similarity for npm:lodash")}async function runMcpSmoke(caller,options={}){const logger=options.logger??console;const includeLiveTools=options.includeLiveTools??true;const toolsResponse=await caller.listTools();const toolNames=new Set(toolsResponse.tools.map((tool)=>tool.name));assert(!toolNames.has("feedback"),"listTools advertises removed feedback tool");assert(!toolNames.has("code_grep"),"listTools advertises retired code_grep instead of grep");for(const expected of EXPECTED_MCP_TOOLS){assert(toolNames.has(expected),`listTools missing ${expected}`)}for(const tool of toolsResponse.tools){const expectedReadOnlyHint=tool.name!=="get_example"&&tool.name!=="research";assert(tool.annotations?.readOnlyHint===expectedReadOnlyHint,`${tool.name} must advertise readOnlyHint: ${expectedReadOnlyHint}`);assert(tool.annotations?.idempotentHint===expectedReadOnlyHint,`${tool.name} must advertise idempotentHint: ${expectedReadOnlyHint}`);const expectedOpenWorldHint=tool.name!=="quick_start";assert(tool.annotations?.openWorldHint===expectedOpenWorldHint,`${tool.name} must advertise openWorldHint: ${expectedOpenWorldHint}, got ${String(tool.annotations?.openWorldHint)}`);assert(tool.annotations?.destructiveHint===false,`${tool.name} must advertise destructiveHint: false`)}const quickStart=assertDefaultText(await callTool(caller,"quick_start",{}),"quick_start default");for(const expected of["## Choose a tool","`search`","`list`","`grep`","`read`","`code_diff`","`resolve_target`","`research`"]){assert(quickStart.includes(expected),`quick_start default missing ${expected}`)}assert(!quickStart.includes("code_grep"),"quick_start still routes matching to retired code_grep");if(!includeLiveTools)return;if(await assertLiveOrAuthRequired(caller,logger)){await runLiveSmoke(caller);logger.log("MCP smoke passed")}}export{EXPECTED_MCP_TOOLS,assertCleanErrorEnvelope,assertDefaultText,assertHttpUnauthorizedChallenge,assertJsonResult,assertMcpResolveText,callToolText,isResolveDirectTargetUnwarned,resultText,runMcpSmoke};
package/dist/tools.d.ts CHANGED
@@ -145,7 +145,7 @@ interface ResolveTargetResult {
145
145
  interface ResolveTargetService {
146
146
  resolveTarget(params: ResolveTargetParams, options?: ServiceRequestOptions): Promise<ResolveTargetResult>;
147
147
  }
148
- import { z as z5 } from "zod";
148
+ import { z as z6 } from "zod";
149
149
  /** Annotation fields required by OpenAI's MCP marketplace validation. */
150
150
  interface CompleteToolAnnotations {
151
151
  title?: string;
@@ -200,7 +200,7 @@ type ToolHandler<TArgs> = (args: TArgs, context?: ToolExecutionContext) => Promi
200
200
  * Zod raw shape type (what MCP SDK expects)
201
201
  */
202
202
  type ZodRawShape = {
203
- [k: string]: z5.ZodTypeAny;
203
+ [k: string]: z6.ZodTypeAny;
204
204
  };
205
205
  /**
206
206
  * Tool definition with metadata and handler
package/dist/tools.js CHANGED
@@ -1 +1 @@
1
- import{ProviderReauthenticationRequiredError2,TermsAcceptanceRequiredError2,FetchTimeoutError2,AuthenticationError2,ApiRateLimitError2}from"./shared/chunk-6v8mtag5.js";import{createGetExampleTool2,createResearchTool2,createResolveTargetTool2}from"./shared/chunk-xqn5jvjs.js";import{z}from"zod";function toCallableTool(definition){const input=z.object(definition.schema);const inputSchema=z.toJSONSchema(input,{io:"input"});return{name:definition.name,description:definition.description,inputSchema,annotations:definition.annotations,execute:async(value,options)=>{const args=input.parse(value);const context={authAction:"Authenticate with GitHits, then retry.",...options?.signal?{signal:options.signal}:{}};return definition.handler(args,context)}}}var ProviderReauthenticationRequiredError=ProviderReauthenticationRequiredError2;var AuthenticationError=AuthenticationError2;var ApiRateLimitError=ApiRateLimitError2;var FetchTimeoutError=FetchTimeoutError2;var TermsAcceptanceRequiredError=TermsAcceptanceRequiredError2;export{ApiRateLimitError,AuthenticationError,FetchTimeoutError,ProviderReauthenticationRequiredError,TermsAcceptanceRequiredError,createGetExampleTool2 as createGetExampleTool,createResearchTool2 as createResearchTool,createResolveTargetTool2 as createResolveTargetTool,toCallableTool};
1
+ import{ProviderReauthenticationRequiredError2,TermsAcceptanceRequiredError2,FetchTimeoutError2,AuthenticationError2,ApiRateLimitError2}from"./shared/chunk-39naxvkd.js";import{createGetExampleTool2,createResearchTool2,createResolveTargetTool2}from"./shared/chunk-2cysvw6d.js";import{z}from"zod";function toCallableTool(definition){const input=z.object(definition.schema);const inputSchema=z.toJSONSchema(input,{io:"input"});return{name:definition.name,description:definition.description,inputSchema,annotations:definition.annotations,execute:async(value,options)=>{const args=input.parse(value);const context={authAction:"Authenticate with GitHits, then retry.",...options?.signal?{signal:options.signal}:{}};return definition.handler(args,context)}}}var ProviderReauthenticationRequiredError=ProviderReauthenticationRequiredError2;var AuthenticationError=AuthenticationError2;var ApiRateLimitError=ApiRateLimitError2;var FetchTimeoutError=FetchTimeoutError2;var TermsAcceptanceRequiredError=TermsAcceptanceRequiredError2;export{ApiRateLimitError,AuthenticationError,FetchTimeoutError,ProviderReauthenticationRequiredError,TermsAcceptanceRequiredError,createGetExampleTool2 as createGetExampleTool,createResearchTool2 as createResearchTool,createResolveTargetTool2 as createResolveTargetTool,toCallableTool};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@githits/mcp",
3
- "version": "0.40.1",
3
+ "version": "0.41.0",
4
4
  "description": "Reusable MCP server APIs and tools for GitHits",
5
5
  "type": "module",
6
6
  "files": [