diff --git a/workers/wiki-mcp/src/hub-router.ts b/workers/wiki-mcp/src/hub-router.ts index 878e11e4..f6d5f737 100644 --- a/workers/wiki-mcp/src/hub-router.ts +++ b/workers/wiki-mcp/src/hub-router.ts @@ -4,6 +4,7 @@ export type ScoredHubCandidate = { database: DatabaseSummary; tags: string[]; sc export type AskHubInput = { question: string; + search_terms?: string[]; preferred_database_ids?: string[]; max_databases?: number; budget_tokens?: number; @@ -198,13 +199,56 @@ export function clipText(text: string, maxChars: number): string { return text.slice(0, end); } +export function catalogIdfWeight(docFreq: number, totalDocs: number): number { + if (!Number.isFinite(docFreq) || !Number.isFinite(totalDocs) || totalDocs < 3 || docFreq <= 1) return 1; + const clampedDf = Math.min(docFreq, totalDocs); + const ratio = (clampedDf - 1) / (totalDocs - 1); + return 0.2 + 0.8 * Math.sqrt(Math.max(0, 1 - ratio)); +} + +function normalizePhrase(text: string): string { + return text.normalize("NFKC").trim().replace(/\s+/gu, " "); +} + +function dedupeNormalizedTerms(terms: string[] | undefined, limit: number): string[] { + if (!terms?.length) return []; + const seen = new Set(); + const out: string[] = []; + for (const raw of terms) { + const clean = normalizePhrase(raw); + if (!clean) continue; + const key = clean.toLowerCase(); + if (seen.has(key)) continue; + seen.add(key); + out.push(clean); + if (out.length >= limit) break; + } + return out; +} + +function mergeQueryTokens(question: string, searchTerms?: string[]): string[] { + const base = tokenizeMultilingual(question); + if (!searchTerms?.length) return base; + const seen = new Set(base); + const merged = [...base]; + for (const term of searchTerms) { + for (const tok of tokenizeMultilingual(term)) { + if (seen.has(tok)) continue; + seen.add(tok); + merged.push(tok); + } + } + return merged; +} + export function selectHubCandidatesFromIndex( index: HubCatalogIndex, question: string, - options: { preferredDatabaseIds?: string[]; maxCandidates?: number } = {} + options: { preferredDatabaseIds?: string[]; maxCandidates?: number; searchTerms?: string[] } = {} ): ScoredHubCandidate[] { - const tokens = tokenizeMultilingual(question); - if (!tokens.length || !index.entries.length) return []; + const tokens = mergeQueryTokens(question, options.searchTerms); + const totalDocs = index.entries.length; + if (!tokens.length || !totalDocs) return []; const preferredIds = options.preferredDatabaseIds?.length ? new Set(options.preferredDatabaseIds.map((id) => id.trim()).filter(Boolean)) @@ -241,21 +285,24 @@ export function selectHubCandidatesFromIndex( } for (let i = 0; i < seenCjkTerms.length; i++) cjkTermSeen[seenCjkTerms[i]!] = 0; seenCjkTerms.length = 0; + if (tokenTouched.length === 0) continue; + const idf = catalogIdfWeight(tokenTouched.length, totalDocs); for (let i = 0; i < tokenTouched.length; i++) { const idx = tokenTouched[i]!; if (scores[idx] === 0) touched.push(idx); - scores[idx] = scores[idx]! + MASK_WEIGHT[tokenMasks[idx]!]!; + scores[idx] = scores[idx]! + MASK_WEIGHT[tokenMasks[idx]!]! * idf; tokenMasks[idx] = 0; } tokenTouched.length = 0; } else { const postingsList = index.postings.get(token); if (!postingsList) continue; + const idf = catalogIdfWeight(postingsList.length, totalDocs); for (let i = 0; i < postingsList.length; i++) { const packed: number = postingsList[i]!; const idx = packed >>> 3; if (scores[idx] === 0) touched.push(idx); - scores[idx] = scores[idx]! + MASK_WEIGHT[packed & 7]!; + scores[idx] = scores[idx]! + MASK_WEIGHT[packed & 7]! * idf; } } } @@ -295,7 +342,7 @@ export function selectHubCandidatesFromIndex( export function selectHubCandidates( databases: DatabaseSummary[], question: string, - options: { preferredDatabaseIds?: string[]; maxCandidates?: number } = {} + options: { preferredDatabaseIds?: string[]; maxCandidates?: number; searchTerms?: string[] } = {} ): ScoredHubCandidate[] { return selectHubCandidatesFromIndex(buildHubCatalogIndex(databases), question, options); } @@ -361,24 +408,21 @@ function extractFallbackKeywords(database: DatabaseSummary, tags: string[], quer return distinct; } -function normalizeAttemptKey(text: string): string { - return text.normalize("NFKC").toLowerCase().replace(/\s+/gu, " ").trim(); -} - function buildFallbackAttempts( question: string, database: DatabaseSummary, tags: string[], tokens: string[], - asciiTokens: string[] + asciiTokens: string[], + searchTerms: string[] ): Array<{ task: string; entities: string[] }> { const attempts: Array<{ task: string; entities: string[] }> = []; - const seen = new Set([normalizeAttemptKey(question)]); + const seen = new Set([normalizePhrase(question).toLowerCase()]); const add = (words: string[]) => { - const clean = words.filter(Boolean); + const clean = dedupeNormalizedTerms(words, 8); if (!clean.length) return; const task = clean.join(" "); - const key = normalizeAttemptKey(task); + const key = normalizePhrase(task).toLowerCase(); if (seen.has(key)) return; seen.add(key); attempts.push({ task, entities: clean }); @@ -386,8 +430,11 @@ function buildFallbackAttempts( const matched = extractFallbackKeywords(database, tags, tokens); const matchedSet = new Set(matched); + const cleanSearchTerms = dedupeNormalizedTerms(searchTerms, 2); if (asciiTokens.length >= 2 && asciiTokens.every((t) => matchedSet.has(t))) add(asciiTokens); + if (cleanSearchTerms.length > 0) add(cleanSearchTerms); if (matched.length >= 2) add(matched.slice(0, 2)); + if (cleanSearchTerms.length > 1) add(cleanSearchTerms.slice(0, 1)); if (matched.length >= 1) add(matched.slice(0, 1)); if (asciiTokens.length > 0) add(asciiTokens); return attempts.slice(0, 2); @@ -408,10 +455,12 @@ export async function routeAndQueryHub(env: RuntimeEnv, input: AskHubInput, deps return { matched: false, reason: "no_visible_databases", question, selected_databases: [], results: [] }; } + const searchTerms = dedupeNormalizedTerms(input.search_terms, 12); const maxDatabases = clamp(input.max_databases, 2, 1, 3); const candidates = selectHubCandidatesFromIndex(index, question, { preferredDatabaseIds: input.preferred_database_ids, - maxCandidates: maxDatabases + maxCandidates: maxDatabases, + searchTerms }); if (!candidates.length) { return { matched: false, reason: "no_relevant_dataset", question, selected_databases: [], results: [] }; @@ -420,8 +469,10 @@ export async function routeAndQueryHub(env: RuntimeEnv, input: AskHubInput, deps const publicOrigin = (env.KINIC_WIKI_PUBLIC_ORIGIN ?? "https://wiki.kinic.xyz").replace(/\/+$/u, ""); const buildUrl = deps.databaseUrl ?? ((_e, id) => `${publicOrigin}/db/${encodeURIComponent(id)}`); const perDbBudget = Math.floor(clamp(input.budget_tokens, 4_000, 1_000, 16_000) / candidates.length); - const tokens = tokenizeMultilingual(question); - const entities = tokens.slice(0, 8); + const questionTokens = tokenizeMultilingual(question); + const searchTermTokens = searchTerms.length ? tokenizeMultilingual(searchTerms.join(" ")) : []; + const tokens = [...new Set([...questionTokens, ...searchTermTokens])]; + const entities = [...new Set([...searchTermTokens, ...questionTokens])].slice(0, 8); const depth = clamp(input.depth, 1, 0, 2); const fetchContext = deps.queryContext ?? queryContext; @@ -447,7 +498,7 @@ export async function routeAndQueryHub(env: RuntimeEnv, input: AskHubInput, deps depth }); if (!needsSearchFallback(first)) return first; - const fallbackAttempts = buildFallbackAttempts(question, item.database, item.tags, tokens, asciiTokens); + const fallbackAttempts = buildFallbackAttempts(question, item.database, item.tags, tokens, asciiTokens, searchTerms); let best = first; for (const attempt of fallbackAttempts) { try { diff --git a/workers/wiki-mcp/src/index.ts b/workers/wiki-mcp/src/index.ts index c7c6f1d5..7095057a 100644 --- a/workers/wiki-mcp/src/index.ts +++ b/workers/wiki-mcp/src/index.ts @@ -286,6 +286,13 @@ const contextOutputSchema = z.object({ const askHubInputSchema = { question: z.string().min(1).max(2000), + search_terms: z + .array(z.string().min(1).max(120)) + .max(12) + .optional() + .describe( + "Optional canonical domain terms, statutes, technical concepts, or multilingual synonyms expanded from colloquial wording in `question` to improve dataset routing and retrieval." + ), preferred_database_ids: z.array(z.string().min(1)).max(20).optional(), max_databases: z.number().int().min(1).max(3).optional(), budget_tokens: z.number().int().min(1000).max(16000).optional(), @@ -727,7 +734,7 @@ export function createServer( "ask_hub", { description: - "Public datasets only: automatically select the most relevant public Kinic Wiki Knowledge Hub dataset(s) for a user question and return grounded context with provenance and source evidence. Returns matched=false when no public dataset is relevant. For private or purchased Marketplace databases, use the authenticated /mcp endpoint.", + "Public datasets only: automatically select the most relevant public Kinic Wiki Knowledge Hub dataset(s) for a user question and return grounded context with provenance and source evidence. When the user's question uses colloquial or everyday phrasing, also pass canonical domain terms or synonyms in search_terms to bridge vocabulary gaps. Returns matched=false when no public dataset is relevant. For private or purchased Marketplace databases, use the authenticated /mcp endpoint.", inputSchema: askHubInputSchema, outputSchema: askHubOutputSchema, annotations: TOOL_ANNOTATIONS, diff --git a/workers/wiki-mcp/tests/hub-router.test.ts b/workers/wiki-mcp/tests/hub-router.test.ts index 656cc761..b6899a63 100644 --- a/workers/wiki-mcp/tests/hub-router.test.ts +++ b/workers/wiki-mcp/tests/hub-router.test.ts @@ -3,6 +3,7 @@ import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js"; import { beforeEach, describe, expect, it } from "vitest"; import { buildHubCatalogIndex, + catalogIdfWeight, clearHubCatalogCache, clipText, parseTags, @@ -16,6 +17,12 @@ import type { DatabaseSummary, QueryContext } from "../src/vfs.js"; const CJK_RE = /^(?:\p{Script=Han}{2,}|\p{Script=Katakana}[\p{Script=Katakana}\u30FC]+|\p{Script=Hiragana}{2,}|\p{Script=Hangul}{2,})$/u; +function referenceIdfWeight(docFreq: number, totalDocs: number): number { + if (totalDocs < 3 || docFreq <= 1) return 1; + const clampedDf = Math.min(docFreq, totalDocs); + return 0.2 + 0.8 * Math.sqrt(Math.max(0, 1 - (clampedDf - 1) / (totalDocs - 1))); +} + function naiveReferenceSelect(databases: DatabaseSummary[], question: string, preferredIds: string[] = [], max = 5) { const qTokens = tokenizeMultilingual(question); if (!qTokens.length) return []; @@ -26,20 +33,33 @@ function naiveReferenceSelect(databases: DatabaseSummary[], question: string, pr for (const c of set) if (CJK_RE.test(c) && (tok.includes(c) || c.includes(tok))) return true; return false; }; - return databases + const active = databases .filter((d) => !d.status || d.status.toLowerCase() === "active") - .map((d) => { - const name = new Set(tokenizeMultilingual(d.name)); - const tags = new Set(tokenizeMultilingual(parseTags(d.tagsJson).join(" "))); - const body = new Set(tokenizeMultilingual(`${d.description} ${d.llmSummary ?? ""}`)); - let score = 0; - for (const tok of qTokens) { - if (match(tok, name)) score += 6; - if (match(tok, tags)) score += 5; - if (match(tok, body)) score += 2.5; - } - if (score > 0 && pref.has(d.databaseId)) score += 3; - return { id: d.databaseId, score: Math.round(score * 100) / 100 }; + .map((d) => ({ + d, + name: new Set(tokenizeMultilingual(d.name)), + tags: new Set(tokenizeMultilingual(parseTags(d.tagsJson).join(" "))), + body: new Set(tokenizeMultilingual(`${d.description} ${d.llmSummary ?? ""}`)) + })); + const scores = active.map(() => 0); + for (const tok of qTokens) { + const perDb = active.map((entry) => { + let w = 0; + if (match(tok, entry.name)) w += 6; + if (match(tok, entry.tags)) w += 5; + if (match(tok, entry.body)) w += 2.5; + return w; + }); + const df = perDb.filter((w) => w > 0).length; + if (df === 0) continue; + const idf = referenceIdfWeight(df, active.length); + for (let i = 0; i < active.length; i++) scores[i] = scores[i]! + perDb[i]! * idf; + } + return active + .map((entry, i) => { + let score = scores[i]!; + if (score > 0 && pref.has(entry.d.databaseId)) score += 3; + return { id: entry.d.databaseId, score: Math.round(score * 100) / 100 }; }) .filter((r) => r.score >= 3.5) .sort((a, b) => b.score - a.score || a.id.localeCompare(b.id)) @@ -486,7 +506,131 @@ describe("hub-router", () => { ]); }); - it("hides /hub/mcp under private_required and exposes hubMode instructions + ask_hub only in hubMode", async () => { + it("damps high-frequency catalog terms via IDF and uses caller-supplied search_terms to bridge vocabulary gaps", async () => { + const dbs: DatabaseSummary[] = [ + { + databaseId: "db_corp", + name: "日本の会社法・特商法 Pack", + description: "会社設立・定款・特商法", + llmSummary: "日本の会社実務", + tagsJson: JSON.stringify(["日本", "会社法", "特商法"]), + status: "active" + }, + { + databaseId: "db_labor", + name: "日本の労働法・労務 Pack", + description: "会社と従業員の労務・カスタマーハラスメント対策義務化", + llmSummary: "労働施策総合推進法・カスハラ", + tagsJson: JSON.stringify(["日本", "労働法", "カスタマーハラスメント"]), + status: "active" + }, + { + databaseId: "db_tax", + name: "日本の税金・法人税 Pack", + description: "会社の法人税・確定申告", + llmSummary: "日本の税務", + tagsJson: JSON.stringify(["日本", "法人税", "確定申告"]), + status: "active" + }, + { + databaseId: "db_privacy", + name: "日本のプライバシー法 Pack", + description: "会社の個人情報保護法対応", + llmSummary: "日本のAPPI実務", + tagsJson: JSON.stringify(["日本", "個人情報保護法"]), + status: "active" + } + ]; + + // Direct IDF boundary checks + expect(catalogIdfWeight(1, 100)).toBe(1); + expect(catalogIdfWeight(2, 2)).toBe(1); + expect(catalogIdfWeight(100, 100)).toBeCloseTo(0.2, 6); + expect(catalogIdfWeight(120, 100)).toBeCloseTo(0.2, 6); + + // Universal boilerplate term ("日本" in 4/4 DBs) alone is damped below MIN_RELEVANCE_SCORE (3.5) + expect(selectHubCandidates(dbs, "日本")).toEqual([]); + + // Specific shared domain matches stay above MIN_RELEVANCE_SCORE when search_terms is omitted: + // (a) 2 of 3 DBs sharing a name token + const threeDbs: DatabaseSummary[] = [ + { databaseId: "db_a", name: "Cloudflare Workers", description: "", llmSummary: "", tagsJson: "[]", status: "active" }, + { databaseId: "db_b", name: "Cloudflare Pages", description: "", llmSummary: "", tagsJson: "[]", status: "active" }, + { databaseId: "db_c", name: "Postgres Guide", description: "", llmSummary: "", tagsJson: "[]", status: "active" } + ]; + expect(selectHubCandidates(threeDbs, "Cloudflare").map((c) => c.database.databaseId)).toEqual(["db_a", "db_b"]); + + // (b) 20 of 1,000 DBs sharing a specific single tag + const largeCatalog: DatabaseSummary[] = Array.from({ length: 1_000 }, (_, i) => ({ + databaseId: `db_${String(i).padStart(4, "0")}`, + name: `Dataset ${i}`, + description: "", + llmSummary: "", + tagsJson: i < 20 ? '["kubernetes"]' : '["other"]', + status: "active" + })); + expect(selectHubCandidates(largeCatalog, "kubernetes")).toHaveLength(5); + + // Colloquial query with canonical search_terms routes to db_labor, puts search_terms first in entities, + // and succeeds ONLY when the retry sends both canonical terms verbatim. + const calls: Array<{ db: string; task: string; entities: string[] }> = []; + const res = await routeAndQueryHub( + {}, + { + question: "お客さんから暴言や土下座要求されたとき会社として何をしなきゃいけないの?", + search_terms: ["カスタマーハラスメント", "労働施策総合推進法"], + max_databases: 1 + }, + { + listDatabases: async () => dbs, + queryContext: async (_env, input) => { + calls.push({ db: input.databaseId, task: input.task, entities: input.entities }); + return input.task === "カスタマーハラスメント 労働施策総合推進法" && + input.entities.join("|") === "カスタマーハラスメント|労働施策総合推進法" + ? mockContext(input.task, "/Knowledge/jp/customer-harassment/rules.md", "2026年カスハラ対策義務化", true) + : mockContext(input.task, "/Knowledge/index.md", "# index", false); + } + } + ); + expect(res.matched).toBe(true); + expect(res.selected_databases[0]?.database_id).toBe("db_labor"); + expect(calls).toHaveLength(2); + expect(calls[0]?.entities.slice(0, 2)).toEqual(["カスタマーハラスメント", "労働施策総合推進法"]); + expect(calls[1]).toEqual({ + db: "db_labor", + task: "カスタマーハラスメント 労働施策総合推進法", + entities: ["カスタマーハラスメント", "労働施策総合推進法"] + }); + + // Equivalent whitespace/NFKC and duplicate search_terms do not consume both fallback slots + clearHubCatalogCache(); + const dedupeDb: DatabaseSummary = { + databaseId: "db_dedupe", + name: "alpha beta guide", + description: "alpha beta gamma reference", + llmSummary: "", + tagsJson: JSON.stringify(["alpha", "beta", "gamma"]), + status: "active" + }; + const dedupeCalls: string[] = []; + await routeAndQueryHub( + {}, + { + question: "alpha beta 教えて", + search_terms: ["alpha beta", "ALPHA beta", "gamma"] + }, + { + listDatabases: async () => [dedupeDb], + queryContext: async (_env, input) => { + dedupeCalls.push(input.task); + return mockContext(input.task, "/Knowledge/index.md", "# index", false); + } + } + ); + expect(dedupeCalls).toEqual(["alpha beta 教えて", "alpha beta gamma", "alpha beta"]); + }); + + it("hides /hub/mcp under private_required and exposes hubMode instructions + ask_hub (with search_terms) only in hubMode", async () => { for (const method of ["GET", "POST", "OPTIONS"]) { const response = await handleMcpRequest(new Request("https://example.com/hub/mcp", { method }), { MCP_ACCESS_POLICY: "private_required" }); expect(response.status).toBe(404); @@ -499,7 +643,9 @@ describe("hub-router", () => { await hubClient.connect(clientTransport); expect(hubClient.getInstructions()).toContain("ask_hub"); const { tools } = await hubClient.listTools(); - expect(tools.map((t) => t.name)).toContain("ask_hub"); + const askHub = tools.find((t) => t.name === "ask_hub"); + expect(askHub).toBeDefined(); + expect(askHub?.inputSchema.properties).toHaveProperty("search_terms"); expect(tools).toHaveLength(8); } finally { await hubClient.close(); @@ -591,4 +737,39 @@ describe("hub-router", () => { console.log(JSON.stringify({ event: "hub_router_cjk_benchmark", dbs: 1000, queries: 40, naiveMs: +naiveMs.toFixed(2), fastMs: +fastMs.toFixed(2), speedup: `${speedup.toFixed(1)}x` })); expect(speedup).toBeGreaterThan(20); }); + + it("Property: catalogIdfWeight is finite, bounded in [0.2, 1.0], monotone non-increasing, and search_terms expansion is idempotent", () => { + // Boundary & adversarial non-finite inputs + for (const df of [NaN, Infinity, -Infinity, -5, 0, 1, 2, 10, 1000]) { + for (const n of [NaN, Infinity, -Infinity, -1, 0, 1, 2, 3, 10, 100]) { + const w = catalogIdfWeight(df, n); + expect(Number.isFinite(w)).toBe(true); + expect(w).toBeGreaterThanOrEqual(0.2 - 1e-12); + expect(w).toBeLessThanOrEqual(1.0 + 1e-12); + } + } + // Monotonicity & exact endpoint values for N >= 3 + for (const n of [3, 5, 10, 50, 1000]) { + expect(catalogIdfWeight(1, n)).toBe(1); + expect(catalogIdfWeight(n, n)).toBeCloseTo(0.2, 12); + expect(catalogIdfWeight(n + 5, n)).toBeCloseTo(0.2, 12); + let prev = 1; + for (let df = 1; df <= n; df++) { + const cur = catalogIdfWeight(df, n); + expect(cur).toBeLessThanOrEqual(prev + 1e-12); + prev = cur; + } + } + + // search_terms idempotency: duplicating/case-varying/NFKC-varying search_terms never double-counts scores + const dbs: DatabaseSummary[] = [ + { databaseId: "a", name: "印紙税 電子契約 ガイド", description: "契約書の印紙税ルール", llmSummary: "", tagsJson: JSON.stringify(["印紙税", "電子契約"]), status: "active" }, + { databaseId: "b", name: "一般契約書 ガイド", description: "日本の契約書実務", llmSummary: "", tagsJson: JSON.stringify(["契約書"]), status: "active" }, + { databaseId: "c", name: "税務実務 ガイド", description: "日本の税務全般", llmSummary: "", tagsJson: JSON.stringify(["税務"]), status: "active" } + ]; + const index = buildHubCatalogIndex(dbs); + const once = selectHubCandidatesFromIndex(index, "PDFで契約書を送るとき", { searchTerms: ["印紙税", "電子契約"] }); + const dup = selectHubCandidatesFromIndex(index, "PDFで契約書を送るとき", { searchTerms: ["印紙税", "電子契約", " 印紙税 ", "電子契約", "印紙税 電子契約"] }); + expect(dup).toEqual(once); + }); });