List indexed knowledge sources directly from chat

This commit is contained in:
Mark Gregory
2026-11-17 10:24:17 +00:00
parent d0f04ecd3a
commit e4f9b5d42d
3 changed files with 132 additions and 1 deletions
+51
View File
@@ -422,6 +422,57 @@ enum ChatWebLookup {
}
enum KnowledgeInventory {
static let toolName = "list_knowledge_sources"
static func matches(_ prompt: String) -> Bool {
let words = Set(prompt.lowercased().split { !$0.isLetter })
let inventory = !words.isDisjoint(with: ["list", "show", "browse", "what", "which"])
let subjects = !words.isDisjoint(with: ["topics", "documents", "files", "sources", "contents", "indexed"])
return words.contains("knowledge") && inventory && subjects
}
static func sources(client: any MCPToolClient) async throws -> [String] {
struct Page: Decodable {
let sources: [String]
let total: Int
}
struct Response: Decodable {
struct Content: Decodable { let text: String? }
let structuredContent: Page?
let content: [Content]?
let isError: Bool?
}
var sources: [String] = []
var seen = Set<String>()
var expectedTotal: Int?
repeat {
try Task.checkCancellation()
let arguments = try JSONEncoder().encode(["offset": sources.count, "limit": 200])
let data = try await client.callTool(toolName, argumentsJSON: arguments)
let decoder = JSONDecoder()
let response = try decoder.decode(Response.self, from: data)
guard response.isError != true else { throw StudioError("The knowledge server could not list its sources.") }
let page = response.structuredContent ?? response.content?.compactMap { item in
item.text.flatMap { try? decoder.decode(Page.self, from: Data($0.utf8)) }
}.first
guard let page, page.total >= 0, page.total == (expectedTotal ?? page.total),
sources.count + page.sources.count <= page.total,
!page.sources.isEmpty || sources.count == page.total else {
throw StudioError("The knowledge inventory changed while it was being read. Try again.")
}
for source in page.sources {
guard seen.insert(source).inserted else {
throw StudioError("The knowledge inventory returned a duplicate page. Try again.")
}
sources.append(source)
}
expectedTotal = page.total
} while sources.count < (expectedTotal ?? 0)
return sources
}
}
enum ExternalKnowledgeSearch {
struct Result {
let reference: String