thorbit-kb-mcp 0.2.8 → 0.2.9

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.
@@ -64,46 +64,12 @@ function resolveThorbitKbMcpEnv() {
64
64
 
65
65
  // src/thorbit-kb-mcp-server.ts
66
66
  var import_mcp = require("@modelcontextprotocol/sdk/server/mcp.js");
67
-
68
- // src/thorbit-kb-mcp-response-formatters.ts
69
- function summarizeResult(toolName, result) {
70
- if (toolName === "thorbit_kb_create" && result && typeof result === "object" && "knowledgeBase" in result) {
71
- const kb = result.knowledgeBase;
72
- return `Created Thorbit knowledge base ${String(kb.name ?? kb.publicId ?? "")}.`;
73
- }
74
- if (toolName === "thorbit_kb_list" && result && typeof result === "object" && "knowledgeBases" in result) {
75
- const count = Array.isArray(result.knowledgeBases) ? result.knowledgeBases.length : 0;
76
- return `Found ${count} Thorbit knowledge base${count === 1 ? "" : "s"}.`;
77
- }
78
- if (toolName.startsWith("thorbit_kb_ingest")) return "Knowledge-base ingestion completed. Check structuredContent for source receipts.";
79
- if (toolName === "thorbit_kb_source_status") return "Source status returned. Check structuredContent for details.";
80
- if (toolName === "thorbit_kb_search") return "Knowledge-base search completed. Check structuredContent for results and citations.";
81
- if (toolName === "thorbit_kb_ask") return "Knowledge-base answer generated. Check structuredContent for citations and strategy.";
82
- return "Thorbit knowledge-base tool completed.";
83
- }
84
- function formatThorbitKbMcpToolResult(toolName, envelope) {
85
- if (!envelope.ok) {
86
- return {
87
- isError: true,
88
- content: [{
89
- type: "text",
90
- text: `${envelope.error.code}: ${envelope.error.message}`
91
- }],
92
- structuredContent: envelope
93
- };
94
- }
95
- return {
96
- content: [{
97
- type: "text",
98
- text: summarizeResult(toolName, envelope.result)
99
- }],
100
- structuredContent: envelope.result
101
- };
102
- }
67
+ var import_thorbit_mcp_core2 = require("thorbit-mcp-core");
103
68
 
104
69
  // src/thorbit-kb-mcp-tool-schemas.ts
70
+ var import_thorbit_mcp_core = require("thorbit-mcp-core");
105
71
  var import_zod = require("zod");
106
- var MetadataSchema = import_zod.z.record(import_zod.z.string(), import_zod.z.unknown());
72
+ var MetadataSchema = import_zod.z.record(import_thorbit_mcp_core.JsonValueSchema);
107
73
  var ThorbitKbCreateInputSchema = {
108
74
  name: import_zod.z.string().min(1).max(255).describe("Name for the new Thorbit knowledge base."),
109
75
  description: import_zod.z.string().max(2e3).optional().describe("Optional description for the new knowledge base."),
@@ -167,16 +133,542 @@ var ThorbitKbAskInputSchema = {
167
133
  limit: import_zod.z.number().int().min(1).max(20).default(8).describe("Maximum retrieved chunks used for the answer."),
168
134
  requireCitations: import_zod.z.boolean().default(true).describe("Keep true for grounded answers with citation arrays.")
169
135
  };
136
+ var ThorbitKnowledgeBasePublicIdSchema = import_zod.z.string().min(1).max(128);
137
+ var ThorbitKnowledgeBaseStatusSchema = import_zod.z.string().min(1).max(64);
138
+ var ThorbitKnowledgeBaseSourceTypeSchema = import_zod.z.string().min(1).max(64);
139
+ var ThorbitKnowledgeBaseSourceStatusSchema = import_zod.z.enum([
140
+ "pending",
141
+ "processing",
142
+ "ready",
143
+ "failed"
144
+ ]);
145
+ var ThorbitKnowledgeBaseResultSchema = import_zod.z.object({
146
+ knowledgeBasePublicId: ThorbitKnowledgeBasePublicIdSchema,
147
+ name: import_zod.z.string().min(1).max(255),
148
+ status: ThorbitKnowledgeBaseStatusSchema,
149
+ createdAt: import_zod.z.string().datetime(),
150
+ updatedAt: import_zod.z.string().datetime()
151
+ }).strict();
152
+ var ThorbitKnowledgeBaseListResultSchema = import_zod.z.object({
153
+ knowledgeBases: import_zod.z.array(ThorbitKnowledgeBaseResultSchema).max(100),
154
+ nextCursor: import_zod.z.string().min(1).max(512).nullable()
155
+ }).strict();
156
+ var ThorbitKnowledgeBaseSourceStatusResultSchema = import_zod.z.object({
157
+ knowledgeBasePublicId: ThorbitKnowledgeBasePublicIdSchema,
158
+ sourcePublicId: ThorbitKnowledgeBasePublicIdSchema,
159
+ sourceType: ThorbitKnowledgeBaseSourceTypeSchema,
160
+ status: ThorbitKnowledgeBaseSourceStatusSchema,
161
+ progressPercent: import_zod.z.number().finite().min(0).max(100),
162
+ error: import_zod.z.string().min(1).max(4e3).nullable(),
163
+ updatedAt: import_zod.z.string().datetime()
164
+ }).strict();
165
+ var ThorbitKnowledgeBaseSourceStatusPollInputSchema = import_zod.z.object({
166
+ sourcePublicIds: import_zod.z.array(ThorbitKnowledgeBasePublicIdSchema).min(1).max(100)
167
+ }).strict();
168
+ var ThorbitKnowledgeBaseIngestResultSchema = import_zod.z.object({
169
+ knowledgeBasePublicId: ThorbitKnowledgeBasePublicIdSchema,
170
+ sourcePublicId: ThorbitKnowledgeBasePublicIdSchema,
171
+ sourceType: ThorbitKnowledgeBaseSourceTypeSchema,
172
+ status: ThorbitKnowledgeBaseSourceStatusSchema,
173
+ pollToolName: import_zod.z.literal("thorbit_kb_source_status"),
174
+ pollInput: ThorbitKnowledgeBaseSourceStatusPollInputSchema
175
+ }).strict();
176
+ var ThorbitKnowledgeBaseCitationSchema = import_zod.z.object({
177
+ index: import_zod.z.number().int().positive().max(1e4),
178
+ chunkPublicId: ThorbitKnowledgeBasePublicIdSchema,
179
+ sourcePublicId: ThorbitKnowledgeBasePublicIdSchema.nullable(),
180
+ sourceTitle: import_zod.z.string().min(1).max(1e3),
181
+ sourceType: ThorbitKnowledgeBaseSourceTypeSchema,
182
+ sourceUrl: import_zod.z.string().url().max(2048).nullable(),
183
+ chunkIndex: import_zod.z.number().int().nonnegative().max(1e7).nullable(),
184
+ timestampStart: import_zod.z.number().finite().nonnegative().max(1e7).nullable(),
185
+ excerpt: import_zod.z.string().max(1e4)
186
+ }).strict();
187
+ var ThorbitKnowledgeBaseSearchMatchSchema = import_zod.z.object({
188
+ chunkPublicId: ThorbitKnowledgeBasePublicIdSchema,
189
+ text: import_zod.z.string().max(5e4),
190
+ score: import_zod.z.number().finite().min(0).max(1)
191
+ }).strict();
192
+ var ThorbitKnowledgeBaseSearchResultSchema = import_zod.z.object({
193
+ query: import_zod.z.string().min(1).max(4e3),
194
+ results: import_zod.z.array(ThorbitKnowledgeBaseSearchMatchSchema).max(50),
195
+ citations: import_zod.z.array(ThorbitKnowledgeBaseCitationSchema).max(50)
196
+ }).strict();
197
+ var ThorbitKnowledgeBaseAnswerResultSchema = import_zod.z.object({
198
+ answer: import_zod.z.string().max(5e5),
199
+ citations: import_zod.z.array(ThorbitKnowledgeBaseCitationSchema).max(50),
200
+ followUps: import_zod.z.array(import_zod.z.string().min(1).max(8e3)).max(20),
201
+ modelId: import_zod.z.string().min(1).max(255).nullable()
202
+ }).strict();
203
+ function createThorbitKnowledgeBaseMcpOutputContract(resultSchema) {
204
+ const strictSchema = (0, import_thorbit_mcp_core.createThorbitMcpStructuredResultSchema)(resultSchema);
205
+ const successShape = strictSchema.options[0].shape;
206
+ const errorShape = strictSchema.options[1].shape;
207
+ const advertisedSchema = import_zod.z.object({
208
+ ok: import_zod.z.boolean(),
209
+ toolName: successShape.toolName,
210
+ requestId: successShape.requestId,
211
+ summary: successShape.summary.optional(),
212
+ result: resultSchema.optional(),
213
+ artifacts: successShape.artifacts.optional(),
214
+ next: successShape.next,
215
+ warnings: successShape.warnings.optional(),
216
+ usage: successShape.usage.optional(),
217
+ error: errorShape.error.optional()
218
+ }).strict();
219
+ return { strictSchema, advertisedSchema };
220
+ }
221
+ var thorbitKnowledgeBaseOutputContracts = {
222
+ thorbit_kb_create: createThorbitKnowledgeBaseMcpOutputContract(ThorbitKnowledgeBaseResultSchema),
223
+ thorbit_kb_list: createThorbitKnowledgeBaseMcpOutputContract(ThorbitKnowledgeBaseListResultSchema),
224
+ thorbit_kb_source_status: createThorbitKnowledgeBaseMcpOutputContract(ThorbitKnowledgeBaseSourceStatusResultSchema),
225
+ thorbit_kb_ingest_url: createThorbitKnowledgeBaseMcpOutputContract(ThorbitKnowledgeBaseIngestResultSchema),
226
+ thorbit_kb_ingest_site: createThorbitKnowledgeBaseMcpOutputContract(ThorbitKnowledgeBaseIngestResultSchema),
227
+ thorbit_kb_ingest_youtube: createThorbitKnowledgeBaseMcpOutputContract(ThorbitKnowledgeBaseIngestResultSchema),
228
+ thorbit_kb_ingest_text: createThorbitKnowledgeBaseMcpOutputContract(ThorbitKnowledgeBaseIngestResultSchema),
229
+ thorbit_kb_search: createThorbitKnowledgeBaseMcpOutputContract(ThorbitKnowledgeBaseSearchResultSchema),
230
+ thorbit_kb_ask: createThorbitKnowledgeBaseMcpOutputContract(ThorbitKnowledgeBaseAnswerResultSchema)
231
+ };
232
+ var ThorbitKnowledgeBaseMcpToolStrictOutputSchemas = {
233
+ thorbit_kb_create: thorbitKnowledgeBaseOutputContracts.thorbit_kb_create.strictSchema,
234
+ thorbit_kb_list: thorbitKnowledgeBaseOutputContracts.thorbit_kb_list.strictSchema,
235
+ thorbit_kb_source_status: thorbitKnowledgeBaseOutputContracts.thorbit_kb_source_status.strictSchema,
236
+ thorbit_kb_ingest_url: thorbitKnowledgeBaseOutputContracts.thorbit_kb_ingest_url.strictSchema,
237
+ thorbit_kb_ingest_site: thorbitKnowledgeBaseOutputContracts.thorbit_kb_ingest_site.strictSchema,
238
+ thorbit_kb_ingest_youtube: thorbitKnowledgeBaseOutputContracts.thorbit_kb_ingest_youtube.strictSchema,
239
+ thorbit_kb_ingest_text: thorbitKnowledgeBaseOutputContracts.thorbit_kb_ingest_text.strictSchema,
240
+ thorbit_kb_search: thorbitKnowledgeBaseOutputContracts.thorbit_kb_search.strictSchema,
241
+ thorbit_kb_ask: thorbitKnowledgeBaseOutputContracts.thorbit_kb_ask.strictSchema
242
+ };
243
+ var ThorbitKnowledgeBaseMcpToolOutputSchemas = {
244
+ thorbit_kb_create: thorbitKnowledgeBaseOutputContracts.thorbit_kb_create.advertisedSchema,
245
+ thorbit_kb_list: thorbitKnowledgeBaseOutputContracts.thorbit_kb_list.advertisedSchema,
246
+ thorbit_kb_source_status: thorbitKnowledgeBaseOutputContracts.thorbit_kb_source_status.advertisedSchema,
247
+ thorbit_kb_ingest_url: thorbitKnowledgeBaseOutputContracts.thorbit_kb_ingest_url.advertisedSchema,
248
+ thorbit_kb_ingest_site: thorbitKnowledgeBaseOutputContracts.thorbit_kb_ingest_site.advertisedSchema,
249
+ thorbit_kb_ingest_youtube: thorbitKnowledgeBaseOutputContracts.thorbit_kb_ingest_youtube.advertisedSchema,
250
+ thorbit_kb_ingest_text: thorbitKnowledgeBaseOutputContracts.thorbit_kb_ingest_text.advertisedSchema,
251
+ thorbit_kb_search: thorbitKnowledgeBaseOutputContracts.thorbit_kb_search.advertisedSchema,
252
+ thorbit_kb_ask: thorbitKnowledgeBaseOutputContracts.thorbit_kb_ask.advertisedSchema
253
+ };
254
+
255
+ // src/thorbit-kb-mcp-response-formatters.ts
256
+ var PUBLIC_ERROR_CODES = /* @__PURE__ */ new Set([
257
+ "unauthorized",
258
+ "forbidden",
259
+ "payment_required",
260
+ "not_found",
261
+ "validation_error",
262
+ "provider_error",
263
+ "rate_limited",
264
+ "conflict",
265
+ "internal_error"
266
+ ]);
267
+ var SENSITIVE_DETAIL_KEY = /(?:authorization|cookie|credential|password|secret|token|api.?key|private.?key)/i;
268
+ var CREDENTIAL_TEXT = /(?:Bearer\s+[^\s,;]+|\b(?:sk|pk|key|token|thbt)[_-][A-Za-z0-9._-]{6,}\b|\bAIza[A-Za-z0-9_-]{20,}\b)/gi;
269
+ var SAFE_METADATA_IDENTIFIER = /^[A-Za-z0-9._/:-]+$/;
270
+ var CREDENTIAL_METADATA = /(?:\b(?:Bearer|Basic|Digest)\s+\S+|\b(?:authorization|api[\s_-]?key|token|secret)\s*[:=]|\b[a-z][a-z0-9+.-]*:\/\/[^/@\s]+@|\b(?:sk|pk|rk|key|token|thbt)[_-][A-Za-z0-9._-]{6,}\b|\bAIza[A-Za-z0-9_-]{20,}\b|\b(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9]{20,}\b|\bgithub_pat_[A-Za-z0-9_]{20,}\b|\bxox[baprs]-[A-Za-z0-9-]{10,}\b|\b(?:AKIA|ASIA)[A-Z0-9]{16}\b)/i;
271
+ var IDEMPOTENT_READ_TOOLS = /* @__PURE__ */ new Set([
272
+ "thorbit_kb_list",
273
+ "thorbit_kb_source_status",
274
+ "thorbit_kb_search"
275
+ ]);
276
+ function asRecord(value) {
277
+ return value !== null && typeof value === "object" && !Array.isArray(value) ? value : null;
278
+ }
279
+ function safeText(value, fallback, maxLength = 4e3) {
280
+ if (typeof value !== "string" || value.trim().length === 0) return fallback;
281
+ return value.trim().slice(0, maxLength).replace(CREDENTIAL_TEXT, "[redacted]");
282
+ }
283
+ function safeDetails(value, depth = 0, active = /* @__PURE__ */ new WeakSet()) {
284
+ if (depth > 4) return "[detail depth omitted]";
285
+ if (typeof value === "string") return safeText(value, "[empty detail]");
286
+ if (typeof value === "number" || typeof value === "boolean" || value === null) return value;
287
+ if (Array.isArray(value)) return value.slice(0, 25).map((item) => safeDetails(item, depth + 1, active));
288
+ if (!value || typeof value !== "object") return void 0;
289
+ if (active.has(value)) return "[cyclic detail omitted]";
290
+ active.add(value);
291
+ try {
292
+ const output = {};
293
+ for (const [key, detail] of Object.entries(value).slice(0, 40)) {
294
+ output[key] = SENSITIVE_DETAIL_KEY.test(key) ? "[redacted]" : safeDetails(detail, depth + 1, active);
295
+ }
296
+ return output;
297
+ } catch {
298
+ return "[unavailable detail]";
299
+ } finally {
300
+ active.delete(value);
301
+ }
302
+ }
303
+ function requiredString(record, key) {
304
+ const value = record[key];
305
+ if (typeof value !== "string" || value.trim().length === 0) {
306
+ throw new TypeError(`Knowledge Base result is missing ${key}`);
307
+ }
308
+ return value.trim();
309
+ }
310
+ function optionalString(record, key) {
311
+ const value = record[key];
312
+ return typeof value === "string" && value.trim().length > 0 ? value.trim() : null;
313
+ }
314
+ function safeMetadataIdentifier(value, maxLength = 255) {
315
+ if (typeof value !== "string") return null;
316
+ const candidate = value.trim();
317
+ if (candidate.length === 0 || candidate.length > maxLength || !SAFE_METADATA_IDENTIFIER.test(candidate) || CREDENTIAL_METADATA.test(candidate)) return null;
318
+ return candidate;
319
+ }
320
+ function requiredDateTime(record, key) {
321
+ const value = requiredString(record, key);
322
+ if (Number.isNaN(Date.parse(value))) {
323
+ throw new TypeError(`Knowledge Base result has an invalid ${key}`);
324
+ }
325
+ return value;
326
+ }
327
+ function requiredNumber(record, key) {
328
+ const value = record[key];
329
+ if (typeof value !== "number" || !Number.isFinite(value)) {
330
+ throw new TypeError(`Knowledge Base result is missing ${key}`);
331
+ }
332
+ return value;
333
+ }
334
+ function normalizeSourceStatus(value) {
335
+ switch (value) {
336
+ case "pending":
337
+ case "processing":
338
+ case "ready":
339
+ case "failed":
340
+ return value;
341
+ default:
342
+ throw new TypeError(`Unsupported Knowledge Base source status: ${String(value)}`);
343
+ }
344
+ }
345
+ function normalizeKnowledgeBase(value) {
346
+ const record = asRecord(value);
347
+ if (!record) throw new TypeError("Knowledge Base record must be an object");
348
+ return {
349
+ knowledgeBasePublicId: optionalString(record, "knowledgeBasePublicId") ?? requiredString(record, "publicId"),
350
+ name: requiredString(record, "name"),
351
+ status: requiredString(record, "status"),
352
+ createdAt: requiredDateTime(record, "createdAt"),
353
+ updatedAt: requiredDateTime(record, "updatedAt")
354
+ };
355
+ }
356
+ function normalizeCitation(value) {
357
+ const citation = asRecord(value);
358
+ if (!citation) throw new TypeError("Knowledge Base citation must be an object");
359
+ const sourceUrl = optionalString(citation, "sourceUrl");
360
+ const rawChunkIndex = citation.chunkIndex;
361
+ const rawTimestampStart = citation.timestampStart;
362
+ return {
363
+ index: requiredNumber(citation, "index"),
364
+ chunkPublicId: requiredString(citation, "chunkPublicId"),
365
+ sourcePublicId: optionalString(citation, "sourcePublicId"),
366
+ sourceTitle: requiredString(citation, "sourceTitle"),
367
+ sourceType: requiredString(citation, "sourceType"),
368
+ sourceUrl,
369
+ chunkIndex: typeof rawChunkIndex === "number" && Number.isFinite(rawChunkIndex) ? rawChunkIndex : null,
370
+ timestampStart: typeof rawTimestampStart === "number" && Number.isFinite(rawTimestampStart) ? rawTimestampStart : null,
371
+ excerpt: typeof citation.excerpt === "string" ? citation.excerpt.slice(0, 1e4) : ""
372
+ };
373
+ }
374
+ function normalizeCitationList(value) {
375
+ if (!Array.isArray(value)) {
376
+ throw new TypeError("Knowledge Base result is missing citations");
377
+ }
378
+ return value.slice(0, 50).map(normalizeCitation);
379
+ }
380
+ function normalizeIngestReceipt(result) {
381
+ let receipt = result;
382
+ const wrappedReceipt = asRecord(result.receipt);
383
+ if (wrappedReceipt) {
384
+ receipt = wrappedReceipt;
385
+ } else if (Array.isArray(result.receipts)) {
386
+ if (result.receipts.length !== 1) {
387
+ throw new TypeError("The exact Knowledge Base ingest contract requires one provider source receipt");
388
+ }
389
+ const onlyReceipt = asRecord(result.receipts[0]);
390
+ if (!onlyReceipt) throw new TypeError("Knowledge Base ingest receipt must be an object");
391
+ receipt = onlyReceipt;
392
+ }
393
+ const sourcePublicId = requiredString(receipt, "sourcePublicId");
394
+ return {
395
+ knowledgeBasePublicId: requiredString(receipt, "knowledgeBasePublicId"),
396
+ sourcePublicId,
397
+ sourceType: requiredString(receipt, "sourceType"),
398
+ status: normalizeSourceStatus(receipt.status),
399
+ pollToolName: "thorbit_kb_source_status",
400
+ pollInput: { sourcePublicIds: [sourcePublicId] }
401
+ };
402
+ }
403
+ function normalizeSuccessResult(toolName, value, envelopeUsage) {
404
+ const result = asRecord(value);
405
+ if (!result) throw new TypeError("Knowledge Base result must be an object");
406
+ switch (toolName) {
407
+ case "thorbit_kb_create":
408
+ return normalizeKnowledgeBase(asRecord(result.knowledgeBase) ?? result);
409
+ case "thorbit_kb_list": {
410
+ if (!Array.isArray(result.knowledgeBases)) {
411
+ throw new TypeError("Knowledge Base list is missing knowledgeBases");
412
+ }
413
+ return {
414
+ knowledgeBases: result.knowledgeBases.slice(0, 100).map(normalizeKnowledgeBase),
415
+ nextCursor: optionalString(result, "nextCursor")
416
+ };
417
+ }
418
+ case "thorbit_kb_source_status": {
419
+ let source = result;
420
+ if (Array.isArray(result.sources)) {
421
+ if (result.sources.length !== 1) {
422
+ throw new TypeError("The exact Knowledge Base source-status contract requires one provider source");
423
+ }
424
+ const onlySource = asRecord(result.sources[0]);
425
+ if (!onlySource) throw new TypeError("Knowledge Base source status must be an object");
426
+ source = onlySource;
427
+ }
428
+ const rawError = optionalString(source, "error") ?? optionalString(source, "errorMessage");
429
+ return {
430
+ knowledgeBasePublicId: requiredString(source, "knowledgeBasePublicId"),
431
+ sourcePublicId: requiredString(source, "sourcePublicId"),
432
+ sourceType: requiredString(source, "sourceType"),
433
+ status: normalizeSourceStatus(source.status),
434
+ progressPercent: requiredNumber(source, "progressPercent"),
435
+ error: rawError ? rawError.slice(0, 4e3) : null,
436
+ updatedAt: requiredDateTime(source, "updatedAt")
437
+ };
438
+ }
439
+ case "thorbit_kb_ingest_url":
440
+ case "thorbit_kb_ingest_site":
441
+ case "thorbit_kb_ingest_youtube":
442
+ case "thorbit_kb_ingest_text":
443
+ return normalizeIngestReceipt(result);
444
+ case "thorbit_kb_search": {
445
+ if (!Array.isArray(result.results)) {
446
+ throw new TypeError("Knowledge Base search is missing results");
447
+ }
448
+ return {
449
+ query: requiredString(result, "query"),
450
+ results: result.results.slice(0, 50).map((value2) => {
451
+ const match = asRecord(value2);
452
+ if (!match) throw new TypeError("Knowledge Base search match must be an object");
453
+ const text = typeof match.text === "string" ? match.text : requiredString(match, "content");
454
+ return {
455
+ chunkPublicId: requiredString(match, "chunkPublicId"),
456
+ text: text.slice(0, 5e4),
457
+ score: requiredNumber(match, "score")
458
+ };
459
+ }),
460
+ citations: normalizeCitationList(result.citations)
461
+ };
462
+ }
463
+ case "thorbit_kb_ask": {
464
+ const sufficiency = asRecord(result.sufficiency);
465
+ const followUpValue = Array.isArray(result.followUps) ? result.followUps : sufficiency?.followUpSuggestions;
466
+ const followUps = Array.isArray(followUpValue) ? followUpValue.filter((item) => typeof item === "string" && item.trim().length > 0).map((item) => item.trim().slice(0, 8e3)).slice(0, 20) : [];
467
+ const usage = asRecord(envelopeUsage);
468
+ const explicitModelId = optionalString(result, "modelId");
469
+ return {
470
+ answer: requiredString(result, "answer").slice(0, 5e5),
471
+ citations: normalizeCitationList(result.citations),
472
+ followUps,
473
+ modelId: explicitModelId !== null ? safeMetadataIdentifier(explicitModelId) : safeMetadataIdentifier(usage?.modelId)
474
+ };
475
+ }
476
+ }
477
+ }
478
+ function normalizeUsage(value) {
479
+ const usage = asRecord(value);
480
+ if (!usage) return void 0;
481
+ const output = {};
482
+ for (const key of ["creditsConsumed", "estimatedUsd"]) {
483
+ const candidate = usage[key];
484
+ if (typeof candidate === "number" && Number.isFinite(candidate) && candidate >= 0) {
485
+ output[key] = candidate;
486
+ }
487
+ }
488
+ for (const key of ["inputTokens", "outputTokens"]) {
489
+ const candidate = usage[key];
490
+ if (typeof candidate === "number" && Number.isInteger(candidate) && candidate >= 0) {
491
+ output[key] = candidate;
492
+ }
493
+ }
494
+ for (const key of ["provider", "modelId"]) {
495
+ const candidate = safeMetadataIdentifier(usage[key]);
496
+ if (candidate !== null) output[key] = candidate;
497
+ }
498
+ return Object.keys(output).length > 0 ? output : void 0;
499
+ }
500
+ function successNextActions(toolName, result) {
501
+ const record = asRecord(result);
502
+ if (!record) return [];
503
+ if (toolName.startsWith("thorbit_kb_ingest_")) {
504
+ return [{
505
+ toolName: "thorbit_kb_source_status",
506
+ reason: "Check the real provider-backed source status after ingestion.",
507
+ input: record.pollInput
508
+ }];
509
+ }
510
+ if (toolName === "thorbit_kb_source_status") {
511
+ if (record.status === "pending" || record.status === "processing") {
512
+ return [{
513
+ toolName: "thorbit_kb_source_status",
514
+ reason: "Poll this source until it is ready or failed.",
515
+ input: { sourcePublicIds: [record.sourcePublicId] }
516
+ }];
517
+ }
518
+ if (record.status === "ready") {
519
+ return [
520
+ {
521
+ toolName: "thorbit_kb_search",
522
+ reason: "Retrieve bounded citation-ready chunks from the ready knowledge base.",
523
+ input: { knowledgeBasePublicId: record.knowledgeBasePublicId }
524
+ },
525
+ {
526
+ toolName: "thorbit_kb_ask",
527
+ reason: "Ask a grounded question against the ready knowledge base.",
528
+ input: { knowledgeBasePublicId: record.knowledgeBasePublicId }
529
+ }
530
+ ];
531
+ }
532
+ }
533
+ if (toolName === "thorbit_kb_search") {
534
+ return [{
535
+ toolName: "thorbit_kb_ask",
536
+ reason: "Synthesize a grounded answer when the retrieved chunks are sufficient.",
537
+ input: { question: record.query }
538
+ }];
539
+ }
540
+ return [];
541
+ }
542
+ function normalizedErrorCode(code) {
543
+ if (PUBLIC_ERROR_CODES.has(code)) return code;
544
+ if (code === "ingestion_error" || code === "invalid_response" || code.startsWith("http_")) {
545
+ return "provider_error";
546
+ }
547
+ return "internal_error";
548
+ }
549
+ function errorRecovery(toolName, code) {
550
+ const transient = code === "provider_error" || code === "rate_limited" || code === "internal_error";
551
+ if (!transient || !IDEMPOTENT_READ_TOOLS.has(toolName)) {
552
+ return { retryable: false, next: [] };
553
+ }
554
+ return {
555
+ retryable: true,
556
+ next: [{
557
+ toolName,
558
+ reason: code === "rate_limited" ? "Retry this idempotent read after the rate limit resets." : "Retry this idempotent read after the transient service issue is resolved."
559
+ }]
560
+ };
561
+ }
562
+ function projectionErrorDetails(error) {
563
+ const issueRecord = asRecord(error);
564
+ const issues = Array.isArray(issueRecord?.issues) ? issueRecord.issues.slice(0, 25).map((issue) => {
565
+ const issueValue = asRecord(issue);
566
+ return {
567
+ path: Array.isArray(issueValue?.path) ? issueValue.path.map(String).join(".") : "",
568
+ code: typeof issueValue?.code === "string" ? issueValue.code : "invalid_result"
569
+ };
570
+ }) : [];
571
+ return {
572
+ reason: "Hosted result did not satisfy the exact public Knowledge Base result contract.",
573
+ ...issues.length > 0 ? { schemaIssues: issues } : {}
574
+ };
575
+ }
576
+ function successSummary(toolName, result) {
577
+ const record = asRecord(result);
578
+ switch (toolName) {
579
+ case "thorbit_kb_create":
580
+ return `Created Thorbit knowledge base ${String(record?.name ?? "")}.`;
581
+ case "thorbit_kb_list":
582
+ return `Found ${Array.isArray(record?.knowledgeBases) ? record.knowledgeBases.length : 0} Thorbit knowledge bases.`;
583
+ case "thorbit_kb_source_status":
584
+ return `Knowledge Base source ${String(record?.sourcePublicId ?? "")} is ${String(record?.status ?? "unknown")}.`;
585
+ case "thorbit_kb_ingest_url":
586
+ case "thorbit_kb_ingest_site":
587
+ case "thorbit_kb_ingest_youtube":
588
+ case "thorbit_kb_ingest_text":
589
+ return `Knowledge Base source ${String(record?.sourcePublicId ?? "")} was accepted with status ${String(record?.status ?? "unknown")}.`;
590
+ case "thorbit_kb_search":
591
+ return `Retrieved ${Array.isArray(record?.results) ? record.results.length : 0} bounded Knowledge Base chunks with citations.`;
592
+ case "thorbit_kb_ask":
593
+ return `Generated a grounded Knowledge Base answer with ${Array.isArray(record?.citations) ? record.citations.length : 0} citations.`;
594
+ }
595
+ }
596
+ function formatThorbitKbMcpToolResult(toolName, envelope, _requestInput) {
597
+ const requestId = safeText(envelope.requestId, "unavailable", 256);
598
+ const outputSchema = ThorbitKnowledgeBaseMcpToolStrictOutputSchemas[toolName];
599
+ if (!envelope.ok) {
600
+ const code = normalizedErrorCode(envelope.error.code);
601
+ const message = safeText(envelope.error.message, "Knowledge Base operation failed.");
602
+ const recovery = errorRecovery(toolName, code);
603
+ const structuredContent = outputSchema.parse({
604
+ ok: false,
605
+ toolName,
606
+ requestId,
607
+ error: {
608
+ code,
609
+ message,
610
+ retryable: recovery.retryable,
611
+ ...envelope.error.details !== void 0 ? { details: safeDetails(envelope.error.details) } : {}
612
+ },
613
+ next: recovery.next
614
+ });
615
+ return {
616
+ content: [{ type: "text", text: `${message} Request ID: ${requestId}.` }],
617
+ structuredContent,
618
+ isError: true
619
+ };
620
+ }
621
+ try {
622
+ const result = normalizeSuccessResult(toolName, envelope.result, envelope.usage);
623
+ const summary = successSummary(toolName, result);
624
+ const usage = normalizeUsage(envelope.usage);
625
+ const structuredContent = outputSchema.parse({
626
+ ok: true,
627
+ toolName,
628
+ requestId,
629
+ summary,
630
+ result,
631
+ artifacts: [],
632
+ next: successNextActions(toolName, result),
633
+ warnings: (envelope.warnings ?? []).map((warning) => safeText(warning, "Hosted warning")),
634
+ ...usage ? { usage } : {}
635
+ });
636
+ return {
637
+ content: [{ type: "text", text: summary }],
638
+ structuredContent,
639
+ isError: false
640
+ };
641
+ } catch (error) {
642
+ const message = "Thorbit completed the Knowledge Base operation, but its hosted result could not be projected to the exact public contract.";
643
+ const structuredContent = outputSchema.parse({
644
+ ok: false,
645
+ toolName,
646
+ requestId,
647
+ error: {
648
+ code: "provider_error",
649
+ message,
650
+ retryable: false,
651
+ details: projectionErrorDetails(error)
652
+ },
653
+ next: []
654
+ });
655
+ return {
656
+ content: [{ type: "text", text: `${message} Request ID: ${requestId}.` }],
657
+ structuredContent,
658
+ isError: true
659
+ };
660
+ }
661
+ }
170
662
 
171
663
  // src/thorbit-kb-mcp-server.ts
172
- var VERSION = "0.2.8";
173
- function readOnlyAnnotations(title, idempotent = true) {
664
+ var VERSION = "0.2.9";
665
+ function readOnlyAnnotations(title, idempotent = true, openWorldHint = false) {
174
666
  return {
175
667
  title,
176
668
  readOnlyHint: true,
177
669
  destructiveHint: false,
178
670
  idempotentHint: idempotent,
179
- openWorldHint: false
671
+ openWorldHint
180
672
  };
181
673
  }
182
674
  function ingestAnnotations(title, openWorldHint) {
@@ -188,6 +680,101 @@ function ingestAnnotations(title, openWorldHint) {
188
680
  openWorldHint
189
681
  };
190
682
  }
683
+ function defineKnowledgeBaseQuality(quality) {
684
+ return import_thorbit_mcp_core2.ThorbitMcpToolQualityMetadataSchema.parse({ productId: "kb", ...quality });
685
+ }
686
+ var KNOWLEDGE_BASE_TOOL_QUALITY = {
687
+ thorbit_kb_create: defineKnowledgeBaseQuality({
688
+ requiredScopes: ["knowledge_base:ingest"],
689
+ whenToUse: ["Use to create a new caller-organization or project Knowledge Base."],
690
+ avoidWhen: ["Avoid when a suitable Knowledge Base already exists; list first."],
691
+ userPhrases: ["create a knowledge base", "make a RAG library", "start a KB"],
692
+ costSummary: "Low-cost durable Knowledge Base record creation.",
693
+ resultMode: "inline",
694
+ nextTools: ["thorbit_kb_ingest_url", "thorbit_kb_ingest_text"],
695
+ sideEffects: ["Creates a durable caller-organization Knowledge Base."]
696
+ }),
697
+ thorbit_kb_list: defineKnowledgeBaseQuality({
698
+ requiredScopes: ["knowledge_base:read"],
699
+ whenToUse: ["Use to find a visible Knowledge Base public ID before ingestion or retrieval."],
700
+ avoidWhen: ["Avoid when the exact Knowledge Base public ID is already known."],
701
+ userPhrases: ["list knowledge bases", "find my KB", "show RAG libraries"],
702
+ costSummary: "Low-cost caller-organization database read.",
703
+ resultMode: "paginated",
704
+ nextTools: ["thorbit_kb_search", "thorbit_kb_ask"],
705
+ sideEffects: []
706
+ }),
707
+ thorbit_kb_source_status: defineKnowledgeBaseQuality({
708
+ requiredScopes: ["knowledge_base:read"],
709
+ whenToUse: ["Use to poll one provider-backed source receipt returned by ingestion."],
710
+ avoidWhen: ["Avoid for retrieving chunks or synthesizing an answer."],
711
+ userPhrases: ["check ingest status", "is this source ready", "poll KB source"],
712
+ costSummary: "Low-cost caller-organization source status read.",
713
+ resultMode: "async",
714
+ nextTools: ["thorbit_kb_search", "thorbit_kb_ask"],
715
+ sideEffects: []
716
+ }),
717
+ thorbit_kb_ingest_url: defineKnowledgeBaseQuality({
718
+ requiredScopes: ["knowledge_base:ingest"],
719
+ whenToUse: ["Use to extract and ingest one public URL into a known Knowledge Base."],
720
+ avoidWhen: ["Avoid for whole websites, YouTube videos, or content already in hand."],
721
+ userPhrases: ["ingest this URL", "add this page to the KB", "vectorize this web page"],
722
+ costSummary: "External MCP Scraper extraction plus durable chunking and vectorization.",
723
+ resultMode: "async",
724
+ nextTools: ["thorbit_kb_source_status"],
725
+ sideEffects: ["Creates an append-only durable Knowledge Base source and chunks."]
726
+ }),
727
+ thorbit_kb_ingest_site: defineKnowledgeBaseQuality({
728
+ requiredScopes: ["knowledge_base:ingest"],
729
+ whenToUse: ["Use to map and ingest a bounded set of pages from one website."],
730
+ avoidWhen: ["Avoid for one known URL, which is cheaper through URL ingestion."],
731
+ userPhrases: ["ingest this website", "crawl pages into the KB", "build a KB from this site"],
732
+ costSummary: "Bounded MCP Scraper mapping and extraction plus durable vectorization per page.",
733
+ resultMode: "async",
734
+ nextTools: ["thorbit_kb_source_status"],
735
+ sideEffects: ["Creates append-only Knowledge Base sources and chunks for accepted pages."]
736
+ }),
737
+ thorbit_kb_ingest_youtube: defineKnowledgeBaseQuality({
738
+ requiredScopes: ["knowledge_base:ingest"],
739
+ whenToUse: ["Use to transcribe and ingest one YouTube video into a known Knowledge Base."],
740
+ avoidWhen: ["Avoid for web pages or caller-supplied text."],
741
+ userPhrases: ["ingest this YouTube video", "add this transcript to the KB", "vectorize this video"],
742
+ costSummary: "External transcription plus durable chunking and vectorization.",
743
+ resultMode: "async",
744
+ nextTools: ["thorbit_kb_source_status"],
745
+ sideEffects: ["Creates an append-only durable transcript source and chunks."]
746
+ }),
747
+ thorbit_kb_ingest_text: defineKnowledgeBaseQuality({
748
+ requiredScopes: ["knowledge_base:ingest"],
749
+ whenToUse: ["Use to ingest text or Markdown already supplied by the caller."],
750
+ avoidWhen: ["Avoid when Thorbit must fetch a URL, website, or YouTube transcript."],
751
+ userPhrases: ["ingest this text", "add these notes to the KB", "vectorize this Markdown"],
752
+ costSummary: "Durable chunking and vectorization without external scraping.",
753
+ resultMode: "async",
754
+ nextTools: ["thorbit_kb_source_status"],
755
+ sideEffects: ["Creates an append-only durable Knowledge Base source and chunks."]
756
+ }),
757
+ thorbit_kb_search: defineKnowledgeBaseQuality({
758
+ requiredScopes: ["knowledge_base:read"],
759
+ whenToUse: ["Use to retrieve bounded citation-ready chunks without answer synthesis."],
760
+ avoidWhen: ["Avoid when the caller wants a direct grounded answer."],
761
+ userPhrases: ["search the KB", "retrieve source chunks", "find citation evidence"],
762
+ costSummary: "Bounded vector or hybrid retrieval and optional reranking.",
763
+ resultMode: "inline",
764
+ nextTools: ["thorbit_kb_ask"],
765
+ sideEffects: []
766
+ }),
767
+ thorbit_kb_ask: defineKnowledgeBaseQuality({
768
+ requiredScopes: ["knowledge_base:read", "knowledge_base:ask"],
769
+ whenToUse: ["Use to synthesize a direct answer grounded in bounded Knowledge Base citations."],
770
+ avoidWhen: ["Avoid when raw retrieved passages are required for caller-side reasoning."],
771
+ userPhrases: ["ask the knowledge base", "answer from my KB", "give me a cited answer"],
772
+ costSummary: "Bounded retrieval plus potentially metered model answer generation.",
773
+ resultMode: "inline",
774
+ nextTools: ["thorbit_kb_search"],
775
+ sideEffects: []
776
+ })
777
+ };
191
778
  var SERVER_INSTRUCTIONS = [
192
779
  "Thorbit Knowledge Base MCP. Vector-backed knowledge bases for ingestion, smart RAG search, and grounded Q&A with citations. This server is a thin client, authenticated and metered against your Thorbit MCP API key.",
193
780
  "",
@@ -207,9 +794,7 @@ var SERVER_INSTRUCTIONS = [
207
794
  "- Need citation-ready chunks yourself, not a synthesized answer -> **thorbit_kb_search**.",
208
795
  '- Need a direct answer grounded in retrieved context -> **thorbit_kb_ask** (set answerStyle:"extractive" for source excerpts without an LLM-written answer). Use thorbit_kb_search instead when you want the raw chunks to reason over yourself.'
209
796
  ].join("\n");
210
- function buildThorbitKnowledgeBaseMcpServer(options) {
211
- const callTool = (toolName, input) => options.callTool(toolName, input);
212
- const server = new import_mcp.McpServer({ name: "thorbit-kb-mcp", version: VERSION }, { instructions: SERVER_INSTRUCTIONS });
797
+ function registerThorbitKnowledgeBaseResources(server, callTool) {
213
798
  server.registerResource(
214
799
  "knowledge-bases",
215
800
  "thorbit-kb://knowledge-bases",
@@ -233,70 +818,109 @@ function buildThorbitKnowledgeBaseMcpServer(options) {
233
818
  },
234
819
  async (uri, variables) => {
235
820
  const sourcePublicId = Array.isArray(variables.sourcePublicId) ? variables.sourcePublicId[0] : variables.sourcePublicId;
236
- const envelope = await callTool("thorbit_kb_source_status", { sourcePublicIds: [String(sourcePublicId)] });
821
+ const envelope = await callTool("thorbit_kb_source_status", {
822
+ sourcePublicIds: [String(sourcePublicId)]
823
+ });
237
824
  return { contents: [{ uri: uri.href, mimeType: "application/json", text: JSON.stringify(envelope, null, 2) }] };
238
825
  }
239
826
  );
827
+ }
828
+ function registerThorbitKnowledgeBaseMcpTools(server, callTool) {
240
829
  function registerTool(toolName, config) {
241
- server.registerTool(toolName, config, async (input) => {
242
- const envelope = await callTool(toolName, input);
243
- return formatThorbitKbMcpToolResult(toolName, envelope);
244
- });
830
+ server.registerTool(toolName, {
831
+ title: config.title,
832
+ description: config.description,
833
+ inputSchema: config.inputSchema,
834
+ outputSchema: config.outputSchema,
835
+ annotations: config.annotations,
836
+ _meta: { thorbit: config.quality }
837
+ }, async (input) => formatThorbitKbMcpToolResult(
838
+ toolName,
839
+ await callTool(toolName, input),
840
+ input
841
+ ));
245
842
  }
246
843
  registerTool("thorbit_kb_create", {
247
844
  title: "Create Thorbit Knowledge Base",
248
845
  description: "Create a new vector-backed knowledge base for ingestion, RAG search, and grounded Q&A. Org-level by default; pass projectPublicId to scope it to one project. Use thorbit_kb_list first if you're not sure whether a suitable knowledge base already exists.",
249
846
  inputSchema: ThorbitKbCreateInputSchema,
250
- annotations: ingestAnnotations("Create Thorbit Knowledge Base", false)
847
+ outputSchema: ThorbitKnowledgeBaseMcpToolOutputSchemas.thorbit_kb_create,
848
+ annotations: ingestAnnotations("Create Thorbit Knowledge Base", false),
849
+ quality: KNOWLEDGE_BASE_TOOL_QUALITY.thorbit_kb_create
251
850
  });
252
851
  registerTool("thorbit_kb_list", {
253
852
  title: "List Thorbit Knowledge Bases",
254
853
  description: "List knowledge bases visible to this API key, org-level and project-scoped. Use before ingestion/search when you don't already have the target knowledgeBasePublicId \u2014 every ingest tool needs one (search/ask can omit it to query all visible KBs instead).",
255
854
  inputSchema: ThorbitKbListInputSchema,
256
- annotations: readOnlyAnnotations("List Thorbit Knowledge Bases")
855
+ outputSchema: ThorbitKnowledgeBaseMcpToolOutputSchemas.thorbit_kb_list,
856
+ annotations: readOnlyAnnotations("List Thorbit Knowledge Bases"),
857
+ quality: KNOWLEDGE_BASE_TOOL_QUALITY.thorbit_kb_list
257
858
  });
258
859
  registerTool("thorbit_kb_source_status", {
259
860
  title: "Read Thorbit KB Source Status",
260
- description: "Poll ingestion status for source public IDs returned by any thorbit_kb_ingest_* tool \u2014 the only way to check whether an ingest finished, since the ingest tools may return before vectorization completes.",
861
+ description: "Poll ingestion status for a source public ID returned by a thorbit_kb_ingest_* tool. Returns the real source state, progress, safe error, and updated time; continue polling until ready or failed, then use thorbit_kb_search or thorbit_kb_ask.",
261
862
  inputSchema: ThorbitKbSourceStatusInputSchema,
262
- annotations: readOnlyAnnotations("Read Thorbit KB Source Status")
863
+ outputSchema: ThorbitKnowledgeBaseMcpToolOutputSchemas.thorbit_kb_source_status,
864
+ annotations: readOnlyAnnotations("Read Thorbit KB Source Status"),
865
+ quality: KNOWLEDGE_BASE_TOOL_QUALITY.thorbit_kb_source_status
263
866
  });
264
867
  registerTool("thorbit_kb_ingest_url", {
265
868
  title: "Ingest URL Into Thorbit KB",
266
- description: "Extract ONE public URL through MCP Scraper, clean it, and vectorize it into a knowledge base (up to 500,000 chars before chunking). For a whole site instead of one page, use thorbit_kb_ingest_site. Append-only: re-ingesting the same URL adds a new source version rather than replacing the prior one \u2014 there is no refresh mode in this version.",
869
+ description: "Extract ONE public URL through MCP Scraper, clean it, and vectorize it into a knowledge base (up to 500,000 chars before chunking). For a whole site instead of one page, use thorbit_kb_ingest_site. Append-only: re-ingesting adds a new source version. Returns a real source receipt and thorbit_kb_source_status follow-up.",
267
870
  inputSchema: ThorbitKbIngestUrlInputSchema,
268
- annotations: ingestAnnotations("Ingest URL Into Thorbit KB", true)
871
+ outputSchema: ThorbitKnowledgeBaseMcpToolOutputSchemas.thorbit_kb_ingest_url,
872
+ annotations: ingestAnnotations("Ingest URL Into Thorbit KB", true),
873
+ quality: KNOWLEDGE_BASE_TOOL_QUALITY.thorbit_kb_ingest_url
269
874
  });
270
875
  registerTool("thorbit_kb_ingest_site", {
271
876
  title: "Ingest Website Into Thorbit KB",
272
- description: "Map a website through MCP Scraper, extract selected pages (up to 100, default 25, filterable via includePatterns/excludePatterns), and vectorize each into a knowledge base. For a single known page instead of crawling a site, use thorbit_kb_ingest_url \u2014 cheaper and faster. Append-only, same as thorbit_kb_ingest_url.",
877
+ description: "Map a website through MCP Scraper, extract selected pages (up to 100, default 25), and vectorize them. For one known page, use thorbit_kb_ingest_url because it is cheaper and faster. The exact public receipt succeeds only when Phoenix supplies one unambiguous source; multi-source provider batches fail closed rather than hiding source IDs.",
273
878
  inputSchema: ThorbitKbIngestSiteInputSchema,
274
- annotations: ingestAnnotations("Ingest Website Into Thorbit KB", true)
879
+ outputSchema: ThorbitKnowledgeBaseMcpToolOutputSchemas.thorbit_kb_ingest_site,
880
+ annotations: ingestAnnotations("Ingest Website Into Thorbit KB", true),
881
+ quality: KNOWLEDGE_BASE_TOOL_QUALITY.thorbit_kb_ingest_site
275
882
  });
276
883
  registerTool("thorbit_kb_ingest_youtube", {
277
884
  title: "Ingest YouTube Into Thorbit KB",
278
- description: "Transcribe a YouTube video through MCP Scraper and vectorize the transcript (timestamp chunks preserved by default) into a knowledge base. For web pages or raw text instead of video, use thorbit_kb_ingest_url or thorbit_kb_ingest_text.",
885
+ description: "Transcribe one YouTube video through MCP Scraper and vectorize the transcript, preserving timestamp chunks by default. For web pages or raw text, use thorbit_kb_ingest_url or thorbit_kb_ingest_text. Returns the real source receipt and a thorbit_kb_source_status follow-up.",
279
886
  inputSchema: ThorbitKbIngestYoutubeInputSchema,
280
- annotations: ingestAnnotations("Ingest YouTube Into Thorbit KB", true)
887
+ outputSchema: ThorbitKnowledgeBaseMcpToolOutputSchemas.thorbit_kb_ingest_youtube,
888
+ annotations: ingestAnnotations("Ingest YouTube Into Thorbit KB", true),
889
+ quality: KNOWLEDGE_BASE_TOOL_QUALITY.thorbit_kb_ingest_youtube
281
890
  });
282
891
  registerTool("thorbit_kb_ingest_text", {
283
892
  title: "Ingest Text Into Thorbit KB",
284
- description: "Submit text or Markdown you already have directly into a knowledge base \u2014 no scraping involved. Use this instead of thorbit_kb_ingest_url when you already have the content in hand rather than a URL to fetch.",
893
+ description: "Submit bounded text or Markdown already in hand directly into a knowledge base with no scraping. Use thorbit_kb_ingest_url when content must be fetched. Returns the real source receipt and a thorbit_kb_source_status follow-up after durable chunking and vectorization.",
285
894
  inputSchema: ThorbitKbIngestTextInputSchema,
286
- annotations: ingestAnnotations("Ingest Text Into Thorbit KB", false)
895
+ outputSchema: ThorbitKnowledgeBaseMcpToolOutputSchemas.thorbit_kb_ingest_text,
896
+ annotations: ingestAnnotations("Ingest Text Into Thorbit KB", false),
897
+ quality: KNOWLEDGE_BASE_TOOL_QUALITY.thorbit_kb_ingest_text
287
898
  });
288
899
  registerTool("thorbit_kb_search", {
289
900
  title: "Search Thorbit Knowledge Base",
290
- description: "Search knowledge-base content and get citation-ready chunks back directly, without a synthesized answer. Use this instead of thorbit_kb_ask when you want to reason over the raw retrieved passages yourself. Omit knowledgeBasePublicId to search all KBs visible to this key.",
901
+ description: "Search visible knowledge-base content and return at most 50 bounded, scored chunks plus bounded provider citations, without synthesizing an answer. Use thorbit_kb_ask for a direct grounded response. Omit knowledgeBasePublicId to search visible KBs.",
291
902
  inputSchema: ThorbitKbSearchInputSchema,
292
- annotations: readOnlyAnnotations("Search Thorbit Knowledge Base")
903
+ outputSchema: ThorbitKnowledgeBaseMcpToolOutputSchemas.thorbit_kb_search,
904
+ annotations: readOnlyAnnotations("Search Thorbit Knowledge Base", true, true),
905
+ quality: KNOWLEDGE_BASE_TOOL_QUALITY.thorbit_kb_search
293
906
  });
294
907
  registerTool("thorbit_kb_ask", {
295
908
  title: "Ask Thorbit Knowledge Base",
296
- description: 'Answer a question using ONLY retrieved knowledge-base context \u2014 returns the answer, citations, sufficiency, and retrieval metadata. Set answerStyle:"extractive" for source excerpts without an LLM-written answer. Use thorbit_kb_search instead when you want the raw chunks rather than a synthesized answer.',
909
+ description: "Answer a question using only retrieved Knowledge Base context and return a bounded answer, citations, follow-ups, and nullable real model ID. Use extractive style for excerpts; use thorbit_kb_search for raw scored chunks. This may invoke a metered answer model.",
297
910
  inputSchema: ThorbitKbAskInputSchema,
298
- annotations: readOnlyAnnotations("Ask Thorbit Knowledge Base", false)
911
+ outputSchema: ThorbitKnowledgeBaseMcpToolOutputSchemas.thorbit_kb_ask,
912
+ annotations: readOnlyAnnotations("Ask Thorbit Knowledge Base", false, true),
913
+ quality: KNOWLEDGE_BASE_TOOL_QUALITY.thorbit_kb_ask
299
914
  });
915
+ }
916
+ function buildThorbitKnowledgeBaseMcpServer(options) {
917
+ const callTool = (toolName, input) => options.callTool(toolName, input);
918
+ const server = new import_mcp.McpServer(
919
+ { name: "thorbit-kb-mcp", version: VERSION },
920
+ { instructions: SERVER_INSTRUCTIONS }
921
+ );
922
+ registerThorbitKnowledgeBaseResources(server, callTool);
923
+ registerThorbitKnowledgeBaseMcpTools(server, callTool);
300
924
  return server;
301
925
  }
302
926