T-136: M2.1e — MCP copilot read_knowledge tool: read-only methodology cards + empirical findings / provider caveats lookup via injected ports in libs/research/src/mcp/tools/
This commit is contained in:
parent
6abee73df2
commit
515b685ffc
3 changed files with 1536 additions and 0 deletions
|
|
@ -4,4 +4,5 @@ export * from './stdio';
|
|||
export * from './tools/analyze-signal';
|
||||
export * from './tools/event-study';
|
||||
export * from './tools/query-data';
|
||||
export * from './tools/read-knowledge';
|
||||
export * from './tools/search-symbols';
|
||||
|
|
|
|||
595
libs/research/src/mcp/tools/read-knowledge.ts
Normal file
595
libs/research/src/mcp/tools/read-knowledge.ts
Normal file
|
|
@ -0,0 +1,595 @@
|
|||
import { z } from 'zod';
|
||||
import type { McpToolCallResult } from '../protocol';
|
||||
import { type McpToolEntry, defineMcpTool } from '../server';
|
||||
|
||||
/** Concrete knowledge sources returned in `read_knowledge` rows and source counts. */
|
||||
export const READ_KNOWLEDGE_RECORD_SOURCES = ['library', 'findings', 'provider_caveats'] as const;
|
||||
|
||||
export type ReadKnowledgeRecordSource = (typeof READ_KNOWLEDGE_RECORD_SOURCES)[number];
|
||||
|
||||
/** Supported `source` selector values for `read_knowledge`. */
|
||||
export const READ_KNOWLEDGE_SOURCES = [...READ_KNOWLEDGE_RECORD_SOURCES, 'all'] as const;
|
||||
|
||||
export type ReadKnowledgeSource = (typeof READ_KNOWLEDGE_SOURCES)[number];
|
||||
|
||||
/** Default maximum number of matching records returned by `read_knowledge`. */
|
||||
export const READ_KNOWLEDGE_DEFAULT_LIMIT = 20;
|
||||
|
||||
/** Hard maximum number of matching records returned by `read_knowledge`. */
|
||||
export const READ_KNOWLEDGE_MAX_LIMIT = 100;
|
||||
|
||||
/** Hard maximum character length of a trimmed `read_knowledge` query string. */
|
||||
export const READ_KNOWLEDGE_MAX_QUERY_LENGTH = 64;
|
||||
|
||||
/** Hard maximum character length per projected text field (`body`, `summary`, `caveat`). */
|
||||
export const READ_KNOWLEDGE_MAX_TEXT_LENGTH = 4096;
|
||||
|
||||
/** Methodology or literature card record returned by {@link KnowledgePort.listLibraryCards}. */
|
||||
export interface LibraryCardRecord {
|
||||
readonly id: string;
|
||||
readonly title: string;
|
||||
readonly tags: readonly string[];
|
||||
readonly summary: string;
|
||||
readonly body: string;
|
||||
}
|
||||
|
||||
/** Empirical Stock Bot finding record returned by {@link KnowledgePort.listFindings}. */
|
||||
export interface FindingRecord {
|
||||
readonly id: string;
|
||||
readonly title: string;
|
||||
readonly status: string;
|
||||
readonly createdAt: string;
|
||||
readonly summary: string;
|
||||
readonly trialRefs: readonly string[];
|
||||
readonly evidenceRefs: readonly string[];
|
||||
}
|
||||
|
||||
/** Provider dataset caveat record returned by {@link KnowledgePort.listProviderCaveats}. */
|
||||
export interface ProviderCaveatRecord {
|
||||
readonly id: string;
|
||||
readonly provider: string;
|
||||
readonly dataset: string;
|
||||
readonly caveat: string;
|
||||
readonly createdAt: string;
|
||||
}
|
||||
|
||||
/** Applicable parsed selectors passed to {@link KnowledgePort.listLibraryCards}. */
|
||||
export interface LibraryCardQuery {
|
||||
readonly id?: string;
|
||||
readonly query?: string;
|
||||
readonly tags?: readonly string[];
|
||||
}
|
||||
|
||||
/** Applicable parsed selectors passed to {@link KnowledgePort.listFindings}. */
|
||||
export interface FindingQuery {
|
||||
readonly id?: string;
|
||||
readonly query?: string;
|
||||
}
|
||||
|
||||
/** Applicable parsed selectors passed to {@link KnowledgePort.listProviderCaveats}. */
|
||||
export interface ProviderCaveatQuery {
|
||||
readonly id?: string;
|
||||
readonly query?: string;
|
||||
readonly provider?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Read-only knowledge lookup port injected into {@link createReadKnowledgeTool}.
|
||||
*
|
||||
* Port contract:
|
||||
* - Read-only by construction: exposes only lookup methods and never mutates backing stores.
|
||||
* - Callers and concrete adapters must supply research-visible records and references only;
|
||||
* holdout observations and vault-only evidence must be excluded from the research corpus.
|
||||
* - Return all eligible candidates (with IDs unique within each source) without pre-slicing
|
||||
* so the tool controls deterministic global ranking and the global `limit`.
|
||||
*/
|
||||
export interface KnowledgePort {
|
||||
listLibraryCards(q: LibraryCardQuery): Promise<readonly LibraryCardRecord[]>;
|
||||
listFindings(q: FindingQuery): Promise<readonly FindingRecord[]>;
|
||||
listProviderCaveats(q: ProviderCaveatQuery): Promise<readonly ProviderCaveatRecord[]>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Strict Zod input schema for the `read_knowledge` MCP tool.
|
||||
*
|
||||
* Intentionally omits `scope`, `vault_evaluation_only`, and `vaultCutoffTs`;
|
||||
* `.strict()` rejects any unknown keys.
|
||||
*/
|
||||
export const readKnowledgeInputSchema = z
|
||||
.object({
|
||||
source: z
|
||||
.enum(READ_KNOWLEDGE_SOURCES)
|
||||
.default('all')
|
||||
.describe(
|
||||
'Knowledge source to query: library, findings, provider_caveats, or all (default all).'
|
||||
),
|
||||
query: z
|
||||
.string()
|
||||
.trim()
|
||||
.min(1)
|
||||
.max(READ_KNOWLEDGE_MAX_QUERY_LENGTH)
|
||||
.optional()
|
||||
.describe(
|
||||
`Optional case-insensitive substring query (trimmed, 1–${READ_KNOWLEDGE_MAX_QUERY_LENGTH} characters). Ignored when id is supplied.`
|
||||
),
|
||||
id: z
|
||||
.string()
|
||||
.trim()
|
||||
.min(1)
|
||||
.optional()
|
||||
.describe(
|
||||
'Optional exact case-sensitive card or record ID selector. Takes precedence over query when supplied.'
|
||||
),
|
||||
tags: z
|
||||
.array(z.string().trim().min(1))
|
||||
.min(1)
|
||||
.optional()
|
||||
.describe(
|
||||
'Optional tag filter applied only to library cards (case-insensitive all-tag match; findings and provider_caveats are unaffected when source is all).'
|
||||
),
|
||||
provider: z
|
||||
.string()
|
||||
.trim()
|
||||
.min(1)
|
||||
.optional()
|
||||
.describe(
|
||||
'Optional provider filter applied only to provider_caveats (case-insensitive exact match; library and findings are unaffected when source is all).'
|
||||
),
|
||||
limit: z
|
||||
.number()
|
||||
.int()
|
||||
.min(1)
|
||||
.max(READ_KNOWLEDGE_MAX_LIMIT)
|
||||
.default(READ_KNOWLEDGE_DEFAULT_LIMIT)
|
||||
.describe(
|
||||
`Maximum number of ranked records to return (default ${READ_KNOWLEDGE_DEFAULT_LIMIT}, max ${READ_KNOWLEDGE_MAX_LIMIT}).`
|
||||
),
|
||||
})
|
||||
.strict();
|
||||
|
||||
export type ReadKnowledgeInput = z.infer<typeof readKnowledgeInputSchema>;
|
||||
|
||||
/** Server-side injected configuration for {@link createReadKnowledgeTool}. */
|
||||
export interface ReadKnowledgeToolOptions {
|
||||
readonly port: KnowledgePort;
|
||||
}
|
||||
|
||||
/** Source-labeled library card row emitted by `read_knowledge`. */
|
||||
export interface ReadKnowledgeLibraryRow {
|
||||
readonly source: 'library';
|
||||
readonly id: string;
|
||||
readonly title: string;
|
||||
readonly tags: readonly string[];
|
||||
readonly summary: string;
|
||||
readonly body: string;
|
||||
readonly truncated: boolean;
|
||||
}
|
||||
|
||||
/** Source-labeled empirical finding row emitted by `read_knowledge`. */
|
||||
export interface ReadKnowledgeFindingRow {
|
||||
readonly source: 'findings';
|
||||
readonly id: string;
|
||||
readonly title: string;
|
||||
readonly status: string;
|
||||
readonly createdAt: string;
|
||||
readonly summary: string;
|
||||
readonly trialRefs: readonly string[];
|
||||
readonly evidenceRefs: readonly string[];
|
||||
readonly truncated: boolean;
|
||||
}
|
||||
|
||||
/** Source-labeled provider caveat row emitted by `read_knowledge`. */
|
||||
export interface ReadKnowledgeProviderCaveatRow {
|
||||
readonly source: 'provider_caveats';
|
||||
readonly id: string;
|
||||
readonly provider: string;
|
||||
readonly dataset: string;
|
||||
readonly caveat: string;
|
||||
readonly createdAt: string;
|
||||
readonly truncated: boolean;
|
||||
}
|
||||
|
||||
/** Discriminated union of rows emitted by `read_knowledge`. */
|
||||
export type ReadKnowledgeRow =
|
||||
| ReadKnowledgeLibraryRow
|
||||
| ReadKnowledgeFindingRow
|
||||
| ReadKnowledgeProviderCaveatRow;
|
||||
|
||||
/** Per-source counts of returned rows after applying the global `limit`. */
|
||||
export interface ReadKnowledgeSourceCounts {
|
||||
readonly library: number;
|
||||
readonly findings: number;
|
||||
readonly provider_caveats: number;
|
||||
}
|
||||
|
||||
/** Structured JSON payload serialized into the `read_knowledge` MCP text result. */
|
||||
export interface ReadKnowledgeResultPayload {
|
||||
readonly rowCount: number;
|
||||
readonly sources: ReadKnowledgeSourceCounts;
|
||||
readonly rows: readonly ReadKnowledgeRow[];
|
||||
}
|
||||
|
||||
const SOURCE_ORDER: Readonly<Record<ReadKnowledgeRecordSource, number>> = {
|
||||
library: 0,
|
||||
findings: 1,
|
||||
provider_caveats: 2,
|
||||
};
|
||||
|
||||
function compareStrings(a: string, b: string): number {
|
||||
if (a < b) {
|
||||
return -1;
|
||||
}
|
||||
if (a > b) {
|
||||
return 1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
function validateRequiredString(value: unknown, field: string): string {
|
||||
if (typeof value !== 'string') {
|
||||
throw new Error(`Invalid port string for "${field}".`);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
function validateStringArray(value: unknown, field: string): readonly string[] {
|
||||
if (!Array.isArray(value)) {
|
||||
throw new Error(`Invalid port string array for "${field}".`);
|
||||
}
|
||||
const result: string[] = [];
|
||||
for (let i = 0; i < value.length; i += 1) {
|
||||
const entry: unknown = value[i];
|
||||
if (typeof entry !== 'string') {
|
||||
throw new Error(`Invalid port string array entry for "${field}".`);
|
||||
}
|
||||
result.push(entry);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
function truncateText(value: string): { readonly text: string; readonly truncated: boolean } {
|
||||
if (value.length <= READ_KNOWLEDGE_MAX_TEXT_LENGTH) {
|
||||
return { text: value, truncated: false };
|
||||
}
|
||||
return {
|
||||
text: value.slice(0, READ_KNOWLEDGE_MAX_TEXT_LENGTH),
|
||||
truncated: true,
|
||||
};
|
||||
}
|
||||
|
||||
function validateLibraryCard(raw: LibraryCardRecord): LibraryCardRecord {
|
||||
if (typeof raw !== 'object' || raw === null) {
|
||||
throw new Error('Invalid library card record returned by port.');
|
||||
}
|
||||
return {
|
||||
id: validateRequiredString(raw.id, 'id'),
|
||||
title: validateRequiredString(raw.title, 'title'),
|
||||
tags: validateStringArray(raw.tags, 'tags'),
|
||||
summary: validateRequiredString(raw.summary, 'summary'),
|
||||
body: validateRequiredString(raw.body, 'body'),
|
||||
};
|
||||
}
|
||||
|
||||
function validateFinding(raw: FindingRecord): FindingRecord {
|
||||
if (typeof raw !== 'object' || raw === null) {
|
||||
throw new Error('Invalid finding record returned by port.');
|
||||
}
|
||||
return {
|
||||
id: validateRequiredString(raw.id, 'id'),
|
||||
title: validateRequiredString(raw.title, 'title'),
|
||||
status: validateRequiredString(raw.status, 'status'),
|
||||
createdAt: validateRequiredString(raw.createdAt, 'createdAt'),
|
||||
summary: validateRequiredString(raw.summary, 'summary'),
|
||||
trialRefs: validateStringArray(raw.trialRefs, 'trialRefs'),
|
||||
evidenceRefs: validateStringArray(raw.evidenceRefs, 'evidenceRefs'),
|
||||
};
|
||||
}
|
||||
|
||||
function validateProviderCaveat(raw: ProviderCaveatRecord): ProviderCaveatRecord {
|
||||
if (typeof raw !== 'object' || raw === null) {
|
||||
throw new Error('Invalid provider caveat record returned by port.');
|
||||
}
|
||||
return {
|
||||
id: validateRequiredString(raw.id, 'id'),
|
||||
provider: validateRequiredString(raw.provider, 'provider'),
|
||||
dataset: validateRequiredString(raw.dataset, 'dataset'),
|
||||
caveat: validateRequiredString(raw.caveat, 'caveat'),
|
||||
createdAt: validateRequiredString(raw.createdAt, 'createdAt'),
|
||||
};
|
||||
}
|
||||
|
||||
function matchesAllTags(
|
||||
cardTags: readonly string[],
|
||||
requiredLowerTags: readonly string[]
|
||||
): boolean {
|
||||
const cardLowerTags = new Set(cardTags.map(tag => tag.toLowerCase()));
|
||||
for (let i = 0; i < requiredLowerTags.length; i += 1) {
|
||||
if (!cardLowerTags.has(requiredLowerTags[i] as string)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
function rankLibraryCard(
|
||||
card: LibraryCardRecord,
|
||||
input: ReadKnowledgeInput,
|
||||
normalizedQuery: string | null,
|
||||
requiredLowerTags: readonly string[] | null
|
||||
): number | null {
|
||||
if (requiredLowerTags !== null && !matchesAllTags(card.tags, requiredLowerTags)) {
|
||||
return null;
|
||||
}
|
||||
if (input.id !== undefined) {
|
||||
return card.id === input.id ? 0 : null;
|
||||
}
|
||||
if (normalizedQuery === null) {
|
||||
return 2;
|
||||
}
|
||||
const titleMatches = card.title.toLowerCase().includes(normalizedQuery);
|
||||
const tagMatches = card.tags.some(tag => tag.toLowerCase().includes(normalizedQuery));
|
||||
const summaryMatches = card.summary.toLowerCase().includes(normalizedQuery);
|
||||
if (!titleMatches && !tagMatches && !summaryMatches) {
|
||||
return null;
|
||||
}
|
||||
if (card.id === input.query) {
|
||||
return 0;
|
||||
}
|
||||
return titleMatches ? 1 : 2;
|
||||
}
|
||||
|
||||
function rankFinding(
|
||||
finding: FindingRecord,
|
||||
input: ReadKnowledgeInput,
|
||||
normalizedQuery: string | null
|
||||
): number | null {
|
||||
if (input.id !== undefined) {
|
||||
return finding.id === input.id ? 0 : null;
|
||||
}
|
||||
if (normalizedQuery === null) {
|
||||
return 2;
|
||||
}
|
||||
const titleMatches = finding.title.toLowerCase().includes(normalizedQuery);
|
||||
const summaryMatches = finding.summary.toLowerCase().includes(normalizedQuery);
|
||||
if (!titleMatches && !summaryMatches) {
|
||||
return null;
|
||||
}
|
||||
if (finding.id === input.query) {
|
||||
return 0;
|
||||
}
|
||||
return titleMatches ? 1 : 2;
|
||||
}
|
||||
|
||||
function rankProviderCaveat(
|
||||
caveat: ProviderCaveatRecord,
|
||||
input: ReadKnowledgeInput,
|
||||
normalizedQuery: string | null,
|
||||
normalizedProvider: string | null
|
||||
): number | null {
|
||||
if (normalizedProvider !== null && caveat.provider.toLowerCase() !== normalizedProvider) {
|
||||
return null;
|
||||
}
|
||||
if (input.id !== undefined) {
|
||||
return caveat.id === input.id ? 0 : null;
|
||||
}
|
||||
if (normalizedQuery === null) {
|
||||
return 2;
|
||||
}
|
||||
const datasetMatches = caveat.dataset.toLowerCase().includes(normalizedQuery);
|
||||
const providerMatches = caveat.provider.toLowerCase().includes(normalizedQuery);
|
||||
const caveatMatches = caveat.caveat.toLowerCase().includes(normalizedQuery);
|
||||
if (!datasetMatches && !providerMatches && !caveatMatches) {
|
||||
return null;
|
||||
}
|
||||
if (caveat.id === input.query) {
|
||||
return 0;
|
||||
}
|
||||
return datasetMatches ? 1 : 2;
|
||||
}
|
||||
|
||||
function projectLibraryCard(card: LibraryCardRecord): ReadKnowledgeLibraryRow {
|
||||
const summary = truncateText(card.summary);
|
||||
const body = truncateText(card.body);
|
||||
return {
|
||||
source: 'library',
|
||||
id: card.id,
|
||||
title: card.title,
|
||||
tags: [...card.tags],
|
||||
summary: summary.text,
|
||||
body: body.text,
|
||||
truncated: summary.truncated || body.truncated,
|
||||
};
|
||||
}
|
||||
|
||||
function projectFinding(finding: FindingRecord): ReadKnowledgeFindingRow {
|
||||
const summary = truncateText(finding.summary);
|
||||
return {
|
||||
source: 'findings',
|
||||
id: finding.id,
|
||||
title: finding.title,
|
||||
status: finding.status,
|
||||
createdAt: finding.createdAt,
|
||||
summary: summary.text,
|
||||
trialRefs: [...finding.trialRefs],
|
||||
evidenceRefs: [...finding.evidenceRefs],
|
||||
truncated: summary.truncated,
|
||||
};
|
||||
}
|
||||
|
||||
function projectProviderCaveat(caveat: ProviderCaveatRecord): ReadKnowledgeProviderCaveatRow {
|
||||
const caveatText = truncateText(caveat.caveat);
|
||||
return {
|
||||
source: 'provider_caveats',
|
||||
id: caveat.id,
|
||||
provider: caveat.provider,
|
||||
dataset: caveat.dataset,
|
||||
caveat: caveatText.text,
|
||||
createdAt: caveat.createdAt,
|
||||
truncated: caveatText.truncated,
|
||||
};
|
||||
}
|
||||
|
||||
function validateFactoryOptions(options: ReadKnowledgeToolOptions): KnowledgePort {
|
||||
if (typeof options !== 'object' || options === null) {
|
||||
throw new Error('Invalid `options`: expected a ReadKnowledgeToolOptions object.');
|
||||
}
|
||||
|
||||
const { port } = options;
|
||||
if (
|
||||
typeof port !== 'object' ||
|
||||
port === null ||
|
||||
typeof port.listLibraryCards !== 'function' ||
|
||||
typeof port.listFindings !== 'function' ||
|
||||
typeof port.listProviderCaveats !== 'function'
|
||||
) {
|
||||
throw new Error(
|
||||
'Invalid `port`: expected a KnowledgePort implementing `listLibraryCards`, `listFindings`, and `listProviderCaveats`.'
|
||||
);
|
||||
}
|
||||
|
||||
return port;
|
||||
}
|
||||
|
||||
interface RankedCandidate {
|
||||
readonly rank: number;
|
||||
readonly row: ReadKnowledgeRow;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates the read-only `read_knowledge` MCP tool backed by an injected
|
||||
* {@link KnowledgePort}.
|
||||
*
|
||||
* Queries only the selected source(s), applies exact-ID or case-insensitive
|
||||
* text matching and source-specific filters (`tags` for library cards,
|
||||
* `provider` for provider caveats), ranks deterministically (exact ID > title
|
||||
* match > ascending ID, breaking cross-source ties in `library`, `findings`,
|
||||
* `provider_caveats` order), applies `limit` after ranking, and caps long text
|
||||
* fields independently with `truncated: true`.
|
||||
*/
|
||||
export function createReadKnowledgeTool(options: ReadKnowledgeToolOptions): McpToolEntry {
|
||||
const port = validateFactoryOptions(options);
|
||||
|
||||
return defineMcpTool({
|
||||
name: 'read_knowledge',
|
||||
description:
|
||||
'Read-only lookup across methodology library cards, empirical findings, and provider dataset caveats.',
|
||||
inputSchema: readKnowledgeInputSchema,
|
||||
async handler(input: ReadKnowledgeInput): Promise<McpToolCallResult> {
|
||||
const wantLibrary = input.source === 'all' || input.source === 'library';
|
||||
const wantFindings = input.source === 'all' || input.source === 'findings';
|
||||
const wantCaveats = input.source === 'all' || input.source === 'provider_caveats';
|
||||
|
||||
const libraryQuery: LibraryCardQuery = {
|
||||
...(input.id !== undefined ? { id: input.id } : {}),
|
||||
...(input.query !== undefined ? { query: input.query } : {}),
|
||||
...(input.tags !== undefined ? { tags: input.tags } : {}),
|
||||
};
|
||||
const findingQuery: FindingQuery = {
|
||||
...(input.id !== undefined ? { id: input.id } : {}),
|
||||
...(input.query !== undefined ? { query: input.query } : {}),
|
||||
};
|
||||
const caveatQuery: ProviderCaveatQuery = {
|
||||
...(input.id !== undefined ? { id: input.id } : {}),
|
||||
...(input.query !== undefined ? { query: input.query } : {}),
|
||||
...(input.provider !== undefined ? { provider: input.provider } : {}),
|
||||
};
|
||||
|
||||
const [rawLibrary, rawFindings, rawCaveats] = await Promise.all([
|
||||
wantLibrary ? port.listLibraryCards(libraryQuery) : Promise.resolve(null),
|
||||
wantFindings ? port.listFindings(findingQuery) : Promise.resolve(null),
|
||||
wantCaveats ? port.listProviderCaveats(caveatQuery) : Promise.resolve(null),
|
||||
]);
|
||||
|
||||
const normalizedQuery =
|
||||
input.id === undefined && input.query !== undefined ? input.query.toLowerCase() : null;
|
||||
const requiredLowerTags =
|
||||
input.tags !== undefined ? input.tags.map(tag => tag.toLowerCase()) : null;
|
||||
const normalizedProvider =
|
||||
input.provider !== undefined ? input.provider.toLowerCase() : null;
|
||||
|
||||
const eligible: RankedCandidate[] = [];
|
||||
|
||||
if (rawLibrary !== null) {
|
||||
if (!Array.isArray(rawLibrary)) {
|
||||
throw new Error('Invalid library cards response returned by port.');
|
||||
}
|
||||
for (let i = 0; i < rawLibrary.length; i += 1) {
|
||||
const card = validateLibraryCard(rawLibrary[i] as LibraryCardRecord);
|
||||
const rank = rankLibraryCard(card, input, normalizedQuery, requiredLowerTags);
|
||||
if (rank !== null) {
|
||||
eligible.push({ rank, row: projectLibraryCard(card) });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (rawFindings !== null) {
|
||||
if (!Array.isArray(rawFindings)) {
|
||||
throw new Error('Invalid findings response returned by port.');
|
||||
}
|
||||
for (let i = 0; i < rawFindings.length; i += 1) {
|
||||
const finding = validateFinding(rawFindings[i] as FindingRecord);
|
||||
const rank = rankFinding(finding, input, normalizedQuery);
|
||||
if (rank !== null) {
|
||||
eligible.push({ rank, row: projectFinding(finding) });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (rawCaveats !== null) {
|
||||
if (!Array.isArray(rawCaveats)) {
|
||||
throw new Error('Invalid provider caveats response returned by port.');
|
||||
}
|
||||
for (let i = 0; i < rawCaveats.length; i += 1) {
|
||||
const caveat = validateProviderCaveat(rawCaveats[i] as ProviderCaveatRecord);
|
||||
const rank = rankProviderCaveat(caveat, input, normalizedQuery, normalizedProvider);
|
||||
if (rank !== null) {
|
||||
eligible.push({ rank, row: projectProviderCaveat(caveat) });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
eligible.sort((a, b) => {
|
||||
if (a.rank !== b.rank) {
|
||||
return a.rank - b.rank;
|
||||
}
|
||||
const idCmp = compareStrings(a.row.id, b.row.id);
|
||||
if (idCmp !== 0) {
|
||||
return idCmp;
|
||||
}
|
||||
return SOURCE_ORDER[a.row.source] - SOURCE_ORDER[b.row.source];
|
||||
});
|
||||
|
||||
const limitCount = Math.min(eligible.length, input.limit);
|
||||
const rows: ReadKnowledgeRow[] = [];
|
||||
let libraryCount = 0;
|
||||
let findingsCount = 0;
|
||||
let providerCaveatsCount = 0;
|
||||
|
||||
for (let i = 0; i < limitCount; i += 1) {
|
||||
const row = (eligible[i] as RankedCandidate).row;
|
||||
rows.push(row);
|
||||
if (row.source === 'library') {
|
||||
libraryCount += 1;
|
||||
} else if (row.source === 'findings') {
|
||||
findingsCount += 1;
|
||||
} else {
|
||||
providerCaveatsCount += 1;
|
||||
}
|
||||
}
|
||||
|
||||
const payload: ReadKnowledgeResultPayload = {
|
||||
rowCount: rows.length,
|
||||
sources: {
|
||||
library: libraryCount,
|
||||
findings: findingsCount,
|
||||
provider_caveats: providerCaveatsCount,
|
||||
},
|
||||
rows,
|
||||
};
|
||||
|
||||
return {
|
||||
content: [{ type: 'text', text: JSON.stringify(payload) }],
|
||||
};
|
||||
},
|
||||
});
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue