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.
- package/dist/bin/thorbit-kb-mcp.cjs +688 -64
- package/dist/bin/thorbit-kb-mcp.cjs.map +1 -1
- package/dist/bin/thorbit-kb-mcp.js +693 -64
- package/dist/bin/thorbit-kb-mcp.js.map +1 -1
- package/dist/index.cjs +768 -100
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +5049 -15
- package/dist/index.d.ts +5049 -15
- package/dist/index.js +760 -100
- package/dist/index.js.map +1 -1
- package/package.json +5 -1
package/dist/index.js
CHANGED
|
@@ -30,48 +30,47 @@ var ThorbitKnowledgeBaseApiClient = class {
|
|
|
30
30
|
}
|
|
31
31
|
};
|
|
32
32
|
|
|
33
|
-
// src/thorbit-kb-mcp-
|
|
34
|
-
import {
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
function
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
33
|
+
// src/thorbit-kb-mcp-env.ts
|
|
34
|
+
import { readFileSync } from "fs";
|
|
35
|
+
import { homedir } from "os";
|
|
36
|
+
import { join } from "path";
|
|
37
|
+
function readApiKeyFile() {
|
|
38
|
+
const explicitPath = process.env.THORBIT_KB_MCP_KEY_PATH?.trim();
|
|
39
|
+
const paths = [explicitPath, join(homedir(), ".thorbit-kb-mcp-key")].filter(Boolean);
|
|
40
|
+
for (const path of paths) {
|
|
41
|
+
try {
|
|
42
|
+
const value = readFileSync(path, "utf8").trim();
|
|
43
|
+
if (value) return value;
|
|
44
|
+
} catch {
|
|
45
|
+
continue;
|
|
46
|
+
}
|
|
45
47
|
}
|
|
46
|
-
|
|
47
|
-
if (toolName === "thorbit_kb_source_status") return "Source status returned. Check structuredContent for details.";
|
|
48
|
-
if (toolName === "thorbit_kb_search") return "Knowledge-base search completed. Check structuredContent for results and citations.";
|
|
49
|
-
if (toolName === "thorbit_kb_ask") return "Knowledge-base answer generated. Check structuredContent for citations and strategy.";
|
|
50
|
-
return "Thorbit knowledge-base tool completed.";
|
|
48
|
+
return void 0;
|
|
51
49
|
}
|
|
52
|
-
function
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
content: [{
|
|
57
|
-
type: "text",
|
|
58
|
-
text: `${envelope.error.code}: ${envelope.error.message}`
|
|
59
|
-
}],
|
|
60
|
-
structuredContent: envelope
|
|
61
|
-
};
|
|
50
|
+
function resolveThorbitKbMcpEnv() {
|
|
51
|
+
const apiKey = (process.env.THORBIT_API_KEY || process.env.THORBIT_MCP_API_KEY || process.env.THORBIT_KB_MCP_API_KEY || readApiKeyFile())?.trim();
|
|
52
|
+
if (!apiKey) {
|
|
53
|
+
throw new Error("THORBIT_API_KEY, THORBIT_MCP_API_KEY, or ~/.thorbit-kb-mcp-key is required");
|
|
62
54
|
}
|
|
63
55
|
return {
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
text: summarizeResult(toolName, envelope.result)
|
|
67
|
-
}],
|
|
68
|
-
structuredContent: envelope.result
|
|
56
|
+
apiKey,
|
|
57
|
+
baseUrl: (process.env.THORBIT_BASE_URL || process.env.THORBIT_KB_MCP_BASE_URL || "https://thorbit.ai").trim()
|
|
69
58
|
};
|
|
70
59
|
}
|
|
71
60
|
|
|
61
|
+
// src/thorbit-kb-mcp-server.ts
|
|
62
|
+
import { McpServer, ResourceTemplate } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
63
|
+
import {
|
|
64
|
+
ThorbitMcpToolQualityMetadataSchema
|
|
65
|
+
} from "thorbit-mcp-core";
|
|
66
|
+
|
|
72
67
|
// src/thorbit-kb-mcp-tool-schemas.ts
|
|
68
|
+
import {
|
|
69
|
+
createThorbitMcpStructuredResultSchema,
|
|
70
|
+
JsonValueSchema
|
|
71
|
+
} from "thorbit-mcp-core";
|
|
73
72
|
import { z } from "zod";
|
|
74
|
-
var MetadataSchema = z.record(
|
|
73
|
+
var MetadataSchema = z.record(JsonValueSchema);
|
|
75
74
|
var ThorbitKbCreateInputSchema = {
|
|
76
75
|
name: z.string().min(1).max(255).describe("Name for the new Thorbit knowledge base."),
|
|
77
76
|
description: z.string().max(2e3).optional().describe("Optional description for the new knowledge base."),
|
|
@@ -146,16 +145,566 @@ var ThorbitKnowledgeBaseMcpToolInputSchemas = {
|
|
|
146
145
|
thorbit_kb_search: ThorbitKbSearchInputSchema,
|
|
147
146
|
thorbit_kb_ask: ThorbitKbAskInputSchema
|
|
148
147
|
};
|
|
148
|
+
var ThorbitKnowledgeBasePublicIdSchema = z.string().min(1).max(128);
|
|
149
|
+
var ThorbitKnowledgeBaseStatusSchema = z.string().min(1).max(64);
|
|
150
|
+
var ThorbitKnowledgeBaseSourceTypeSchema = z.string().min(1).max(64);
|
|
151
|
+
var ThorbitKnowledgeBaseSourceStatusSchema = z.enum([
|
|
152
|
+
"pending",
|
|
153
|
+
"processing",
|
|
154
|
+
"ready",
|
|
155
|
+
"failed"
|
|
156
|
+
]);
|
|
157
|
+
var ThorbitKnowledgeBaseResultSchema = z.object({
|
|
158
|
+
knowledgeBasePublicId: ThorbitKnowledgeBasePublicIdSchema,
|
|
159
|
+
name: z.string().min(1).max(255),
|
|
160
|
+
status: ThorbitKnowledgeBaseStatusSchema,
|
|
161
|
+
createdAt: z.string().datetime(),
|
|
162
|
+
updatedAt: z.string().datetime()
|
|
163
|
+
}).strict();
|
|
164
|
+
var ThorbitKnowledgeBaseListResultSchema = z.object({
|
|
165
|
+
knowledgeBases: z.array(ThorbitKnowledgeBaseResultSchema).max(100),
|
|
166
|
+
nextCursor: z.string().min(1).max(512).nullable()
|
|
167
|
+
}).strict();
|
|
168
|
+
var ThorbitKnowledgeBaseSourceStatusResultSchema = z.object({
|
|
169
|
+
knowledgeBasePublicId: ThorbitKnowledgeBasePublicIdSchema,
|
|
170
|
+
sourcePublicId: ThorbitKnowledgeBasePublicIdSchema,
|
|
171
|
+
sourceType: ThorbitKnowledgeBaseSourceTypeSchema,
|
|
172
|
+
status: ThorbitKnowledgeBaseSourceStatusSchema,
|
|
173
|
+
progressPercent: z.number().finite().min(0).max(100),
|
|
174
|
+
error: z.string().min(1).max(4e3).nullable(),
|
|
175
|
+
updatedAt: z.string().datetime()
|
|
176
|
+
}).strict();
|
|
177
|
+
var ThorbitKnowledgeBaseSourceStatusPollInputSchema = z.object({
|
|
178
|
+
sourcePublicIds: z.array(ThorbitKnowledgeBasePublicIdSchema).min(1).max(100)
|
|
179
|
+
}).strict();
|
|
180
|
+
var ThorbitKnowledgeBaseIngestResultSchema = z.object({
|
|
181
|
+
knowledgeBasePublicId: ThorbitKnowledgeBasePublicIdSchema,
|
|
182
|
+
sourcePublicId: ThorbitKnowledgeBasePublicIdSchema,
|
|
183
|
+
sourceType: ThorbitKnowledgeBaseSourceTypeSchema,
|
|
184
|
+
status: ThorbitKnowledgeBaseSourceStatusSchema,
|
|
185
|
+
pollToolName: z.literal("thorbit_kb_source_status"),
|
|
186
|
+
pollInput: ThorbitKnowledgeBaseSourceStatusPollInputSchema
|
|
187
|
+
}).strict();
|
|
188
|
+
var ThorbitKnowledgeBaseCitationSchema = z.object({
|
|
189
|
+
index: z.number().int().positive().max(1e4),
|
|
190
|
+
chunkPublicId: ThorbitKnowledgeBasePublicIdSchema,
|
|
191
|
+
sourcePublicId: ThorbitKnowledgeBasePublicIdSchema.nullable(),
|
|
192
|
+
sourceTitle: z.string().min(1).max(1e3),
|
|
193
|
+
sourceType: ThorbitKnowledgeBaseSourceTypeSchema,
|
|
194
|
+
sourceUrl: z.string().url().max(2048).nullable(),
|
|
195
|
+
chunkIndex: z.number().int().nonnegative().max(1e7).nullable(),
|
|
196
|
+
timestampStart: z.number().finite().nonnegative().max(1e7).nullable(),
|
|
197
|
+
excerpt: z.string().max(1e4)
|
|
198
|
+
}).strict();
|
|
199
|
+
var ThorbitKnowledgeBaseSearchMatchSchema = z.object({
|
|
200
|
+
chunkPublicId: ThorbitKnowledgeBasePublicIdSchema,
|
|
201
|
+
text: z.string().max(5e4),
|
|
202
|
+
score: z.number().finite().min(0).max(1)
|
|
203
|
+
}).strict();
|
|
204
|
+
var ThorbitKnowledgeBaseSearchResultSchema = z.object({
|
|
205
|
+
query: z.string().min(1).max(4e3),
|
|
206
|
+
results: z.array(ThorbitKnowledgeBaseSearchMatchSchema).max(50),
|
|
207
|
+
citations: z.array(ThorbitKnowledgeBaseCitationSchema).max(50)
|
|
208
|
+
}).strict();
|
|
209
|
+
var ThorbitKnowledgeBaseAnswerResultSchema = z.object({
|
|
210
|
+
answer: z.string().max(5e5),
|
|
211
|
+
citations: z.array(ThorbitKnowledgeBaseCitationSchema).max(50),
|
|
212
|
+
followUps: z.array(z.string().min(1).max(8e3)).max(20),
|
|
213
|
+
modelId: z.string().min(1).max(255).nullable()
|
|
214
|
+
}).strict();
|
|
215
|
+
var ThorbitKnowledgeBaseMcpToolResultSchemas = {
|
|
216
|
+
thorbit_kb_create: ThorbitKnowledgeBaseResultSchema,
|
|
217
|
+
thorbit_kb_list: ThorbitKnowledgeBaseListResultSchema,
|
|
218
|
+
thorbit_kb_source_status: ThorbitKnowledgeBaseSourceStatusResultSchema,
|
|
219
|
+
thorbit_kb_ingest_url: ThorbitKnowledgeBaseIngestResultSchema,
|
|
220
|
+
thorbit_kb_ingest_site: ThorbitKnowledgeBaseIngestResultSchema,
|
|
221
|
+
thorbit_kb_ingest_youtube: ThorbitKnowledgeBaseIngestResultSchema,
|
|
222
|
+
thorbit_kb_ingest_text: ThorbitKnowledgeBaseIngestResultSchema,
|
|
223
|
+
thorbit_kb_search: ThorbitKnowledgeBaseSearchResultSchema,
|
|
224
|
+
thorbit_kb_ask: ThorbitKnowledgeBaseAnswerResultSchema
|
|
225
|
+
};
|
|
226
|
+
function createThorbitKnowledgeBaseMcpOutputContract(resultSchema) {
|
|
227
|
+
const strictSchema = createThorbitMcpStructuredResultSchema(resultSchema);
|
|
228
|
+
const successShape = strictSchema.options[0].shape;
|
|
229
|
+
const errorShape = strictSchema.options[1].shape;
|
|
230
|
+
const advertisedSchema = z.object({
|
|
231
|
+
ok: z.boolean(),
|
|
232
|
+
toolName: successShape.toolName,
|
|
233
|
+
requestId: successShape.requestId,
|
|
234
|
+
summary: successShape.summary.optional(),
|
|
235
|
+
result: resultSchema.optional(),
|
|
236
|
+
artifacts: successShape.artifacts.optional(),
|
|
237
|
+
next: successShape.next,
|
|
238
|
+
warnings: successShape.warnings.optional(),
|
|
239
|
+
usage: successShape.usage.optional(),
|
|
240
|
+
error: errorShape.error.optional()
|
|
241
|
+
}).strict();
|
|
242
|
+
return { strictSchema, advertisedSchema };
|
|
243
|
+
}
|
|
244
|
+
var thorbitKnowledgeBaseOutputContracts = {
|
|
245
|
+
thorbit_kb_create: createThorbitKnowledgeBaseMcpOutputContract(ThorbitKnowledgeBaseResultSchema),
|
|
246
|
+
thorbit_kb_list: createThorbitKnowledgeBaseMcpOutputContract(ThorbitKnowledgeBaseListResultSchema),
|
|
247
|
+
thorbit_kb_source_status: createThorbitKnowledgeBaseMcpOutputContract(ThorbitKnowledgeBaseSourceStatusResultSchema),
|
|
248
|
+
thorbit_kb_ingest_url: createThorbitKnowledgeBaseMcpOutputContract(ThorbitKnowledgeBaseIngestResultSchema),
|
|
249
|
+
thorbit_kb_ingest_site: createThorbitKnowledgeBaseMcpOutputContract(ThorbitKnowledgeBaseIngestResultSchema),
|
|
250
|
+
thorbit_kb_ingest_youtube: createThorbitKnowledgeBaseMcpOutputContract(ThorbitKnowledgeBaseIngestResultSchema),
|
|
251
|
+
thorbit_kb_ingest_text: createThorbitKnowledgeBaseMcpOutputContract(ThorbitKnowledgeBaseIngestResultSchema),
|
|
252
|
+
thorbit_kb_search: createThorbitKnowledgeBaseMcpOutputContract(ThorbitKnowledgeBaseSearchResultSchema),
|
|
253
|
+
thorbit_kb_ask: createThorbitKnowledgeBaseMcpOutputContract(ThorbitKnowledgeBaseAnswerResultSchema)
|
|
254
|
+
};
|
|
255
|
+
var ThorbitKnowledgeBaseMcpToolStrictOutputSchemas = {
|
|
256
|
+
thorbit_kb_create: thorbitKnowledgeBaseOutputContracts.thorbit_kb_create.strictSchema,
|
|
257
|
+
thorbit_kb_list: thorbitKnowledgeBaseOutputContracts.thorbit_kb_list.strictSchema,
|
|
258
|
+
thorbit_kb_source_status: thorbitKnowledgeBaseOutputContracts.thorbit_kb_source_status.strictSchema,
|
|
259
|
+
thorbit_kb_ingest_url: thorbitKnowledgeBaseOutputContracts.thorbit_kb_ingest_url.strictSchema,
|
|
260
|
+
thorbit_kb_ingest_site: thorbitKnowledgeBaseOutputContracts.thorbit_kb_ingest_site.strictSchema,
|
|
261
|
+
thorbit_kb_ingest_youtube: thorbitKnowledgeBaseOutputContracts.thorbit_kb_ingest_youtube.strictSchema,
|
|
262
|
+
thorbit_kb_ingest_text: thorbitKnowledgeBaseOutputContracts.thorbit_kb_ingest_text.strictSchema,
|
|
263
|
+
thorbit_kb_search: thorbitKnowledgeBaseOutputContracts.thorbit_kb_search.strictSchema,
|
|
264
|
+
thorbit_kb_ask: thorbitKnowledgeBaseOutputContracts.thorbit_kb_ask.strictSchema
|
|
265
|
+
};
|
|
266
|
+
var ThorbitKnowledgeBaseMcpToolOutputSchemas = {
|
|
267
|
+
thorbit_kb_create: thorbitKnowledgeBaseOutputContracts.thorbit_kb_create.advertisedSchema,
|
|
268
|
+
thorbit_kb_list: thorbitKnowledgeBaseOutputContracts.thorbit_kb_list.advertisedSchema,
|
|
269
|
+
thorbit_kb_source_status: thorbitKnowledgeBaseOutputContracts.thorbit_kb_source_status.advertisedSchema,
|
|
270
|
+
thorbit_kb_ingest_url: thorbitKnowledgeBaseOutputContracts.thorbit_kb_ingest_url.advertisedSchema,
|
|
271
|
+
thorbit_kb_ingest_site: thorbitKnowledgeBaseOutputContracts.thorbit_kb_ingest_site.advertisedSchema,
|
|
272
|
+
thorbit_kb_ingest_youtube: thorbitKnowledgeBaseOutputContracts.thorbit_kb_ingest_youtube.advertisedSchema,
|
|
273
|
+
thorbit_kb_ingest_text: thorbitKnowledgeBaseOutputContracts.thorbit_kb_ingest_text.advertisedSchema,
|
|
274
|
+
thorbit_kb_search: thorbitKnowledgeBaseOutputContracts.thorbit_kb_search.advertisedSchema,
|
|
275
|
+
thorbit_kb_ask: thorbitKnowledgeBaseOutputContracts.thorbit_kb_ask.advertisedSchema
|
|
276
|
+
};
|
|
277
|
+
|
|
278
|
+
// src/thorbit-kb-mcp-response-formatters.ts
|
|
279
|
+
var PUBLIC_ERROR_CODES = /* @__PURE__ */ new Set([
|
|
280
|
+
"unauthorized",
|
|
281
|
+
"forbidden",
|
|
282
|
+
"payment_required",
|
|
283
|
+
"not_found",
|
|
284
|
+
"validation_error",
|
|
285
|
+
"provider_error",
|
|
286
|
+
"rate_limited",
|
|
287
|
+
"conflict",
|
|
288
|
+
"internal_error"
|
|
289
|
+
]);
|
|
290
|
+
var SENSITIVE_DETAIL_KEY = /(?:authorization|cookie|credential|password|secret|token|api.?key|private.?key)/i;
|
|
291
|
+
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;
|
|
292
|
+
var SAFE_METADATA_IDENTIFIER = /^[A-Za-z0-9._/:-]+$/;
|
|
293
|
+
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;
|
|
294
|
+
var IDEMPOTENT_READ_TOOLS = /* @__PURE__ */ new Set([
|
|
295
|
+
"thorbit_kb_list",
|
|
296
|
+
"thorbit_kb_source_status",
|
|
297
|
+
"thorbit_kb_search"
|
|
298
|
+
]);
|
|
299
|
+
function asRecord(value) {
|
|
300
|
+
return value !== null && typeof value === "object" && !Array.isArray(value) ? value : null;
|
|
301
|
+
}
|
|
302
|
+
function safeText(value, fallback, maxLength = 4e3) {
|
|
303
|
+
if (typeof value !== "string" || value.trim().length === 0) return fallback;
|
|
304
|
+
return value.trim().slice(0, maxLength).replace(CREDENTIAL_TEXT, "[redacted]");
|
|
305
|
+
}
|
|
306
|
+
function safeDetails(value, depth = 0, active = /* @__PURE__ */ new WeakSet()) {
|
|
307
|
+
if (depth > 4) return "[detail depth omitted]";
|
|
308
|
+
if (typeof value === "string") return safeText(value, "[empty detail]");
|
|
309
|
+
if (typeof value === "number" || typeof value === "boolean" || value === null) return value;
|
|
310
|
+
if (Array.isArray(value)) return value.slice(0, 25).map((item) => safeDetails(item, depth + 1, active));
|
|
311
|
+
if (!value || typeof value !== "object") return void 0;
|
|
312
|
+
if (active.has(value)) return "[cyclic detail omitted]";
|
|
313
|
+
active.add(value);
|
|
314
|
+
try {
|
|
315
|
+
const output = {};
|
|
316
|
+
for (const [key, detail] of Object.entries(value).slice(0, 40)) {
|
|
317
|
+
output[key] = SENSITIVE_DETAIL_KEY.test(key) ? "[redacted]" : safeDetails(detail, depth + 1, active);
|
|
318
|
+
}
|
|
319
|
+
return output;
|
|
320
|
+
} catch {
|
|
321
|
+
return "[unavailable detail]";
|
|
322
|
+
} finally {
|
|
323
|
+
active.delete(value);
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
function requiredString(record, key) {
|
|
327
|
+
const value = record[key];
|
|
328
|
+
if (typeof value !== "string" || value.trim().length === 0) {
|
|
329
|
+
throw new TypeError(`Knowledge Base result is missing ${key}`);
|
|
330
|
+
}
|
|
331
|
+
return value.trim();
|
|
332
|
+
}
|
|
333
|
+
function optionalString(record, key) {
|
|
334
|
+
const value = record[key];
|
|
335
|
+
return typeof value === "string" && value.trim().length > 0 ? value.trim() : null;
|
|
336
|
+
}
|
|
337
|
+
function safeMetadataIdentifier(value, maxLength = 255) {
|
|
338
|
+
if (typeof value !== "string") return null;
|
|
339
|
+
const candidate = value.trim();
|
|
340
|
+
if (candidate.length === 0 || candidate.length > maxLength || !SAFE_METADATA_IDENTIFIER.test(candidate) || CREDENTIAL_METADATA.test(candidate)) return null;
|
|
341
|
+
return candidate;
|
|
342
|
+
}
|
|
343
|
+
function requiredDateTime(record, key) {
|
|
344
|
+
const value = requiredString(record, key);
|
|
345
|
+
if (Number.isNaN(Date.parse(value))) {
|
|
346
|
+
throw new TypeError(`Knowledge Base result has an invalid ${key}`);
|
|
347
|
+
}
|
|
348
|
+
return value;
|
|
349
|
+
}
|
|
350
|
+
function requiredNumber(record, key) {
|
|
351
|
+
const value = record[key];
|
|
352
|
+
if (typeof value !== "number" || !Number.isFinite(value)) {
|
|
353
|
+
throw new TypeError(`Knowledge Base result is missing ${key}`);
|
|
354
|
+
}
|
|
355
|
+
return value;
|
|
356
|
+
}
|
|
357
|
+
function normalizeSourceStatus(value) {
|
|
358
|
+
switch (value) {
|
|
359
|
+
case "pending":
|
|
360
|
+
case "processing":
|
|
361
|
+
case "ready":
|
|
362
|
+
case "failed":
|
|
363
|
+
return value;
|
|
364
|
+
default:
|
|
365
|
+
throw new TypeError(`Unsupported Knowledge Base source status: ${String(value)}`);
|
|
366
|
+
}
|
|
367
|
+
}
|
|
368
|
+
function normalizeKnowledgeBase(value) {
|
|
369
|
+
const record = asRecord(value);
|
|
370
|
+
if (!record) throw new TypeError("Knowledge Base record must be an object");
|
|
371
|
+
return {
|
|
372
|
+
knowledgeBasePublicId: optionalString(record, "knowledgeBasePublicId") ?? requiredString(record, "publicId"),
|
|
373
|
+
name: requiredString(record, "name"),
|
|
374
|
+
status: requiredString(record, "status"),
|
|
375
|
+
createdAt: requiredDateTime(record, "createdAt"),
|
|
376
|
+
updatedAt: requiredDateTime(record, "updatedAt")
|
|
377
|
+
};
|
|
378
|
+
}
|
|
379
|
+
function normalizeCitation(value) {
|
|
380
|
+
const citation = asRecord(value);
|
|
381
|
+
if (!citation) throw new TypeError("Knowledge Base citation must be an object");
|
|
382
|
+
const sourceUrl = optionalString(citation, "sourceUrl");
|
|
383
|
+
const rawChunkIndex = citation.chunkIndex;
|
|
384
|
+
const rawTimestampStart = citation.timestampStart;
|
|
385
|
+
return {
|
|
386
|
+
index: requiredNumber(citation, "index"),
|
|
387
|
+
chunkPublicId: requiredString(citation, "chunkPublicId"),
|
|
388
|
+
sourcePublicId: optionalString(citation, "sourcePublicId"),
|
|
389
|
+
sourceTitle: requiredString(citation, "sourceTitle"),
|
|
390
|
+
sourceType: requiredString(citation, "sourceType"),
|
|
391
|
+
sourceUrl,
|
|
392
|
+
chunkIndex: typeof rawChunkIndex === "number" && Number.isFinite(rawChunkIndex) ? rawChunkIndex : null,
|
|
393
|
+
timestampStart: typeof rawTimestampStart === "number" && Number.isFinite(rawTimestampStart) ? rawTimestampStart : null,
|
|
394
|
+
excerpt: typeof citation.excerpt === "string" ? citation.excerpt.slice(0, 1e4) : ""
|
|
395
|
+
};
|
|
396
|
+
}
|
|
397
|
+
function normalizeCitationList(value) {
|
|
398
|
+
if (!Array.isArray(value)) {
|
|
399
|
+
throw new TypeError("Knowledge Base result is missing citations");
|
|
400
|
+
}
|
|
401
|
+
return value.slice(0, 50).map(normalizeCitation);
|
|
402
|
+
}
|
|
403
|
+
function normalizeIngestReceipt(result) {
|
|
404
|
+
let receipt = result;
|
|
405
|
+
const wrappedReceipt = asRecord(result.receipt);
|
|
406
|
+
if (wrappedReceipt) {
|
|
407
|
+
receipt = wrappedReceipt;
|
|
408
|
+
} else if (Array.isArray(result.receipts)) {
|
|
409
|
+
if (result.receipts.length !== 1) {
|
|
410
|
+
throw new TypeError("The exact Knowledge Base ingest contract requires one provider source receipt");
|
|
411
|
+
}
|
|
412
|
+
const onlyReceipt = asRecord(result.receipts[0]);
|
|
413
|
+
if (!onlyReceipt) throw new TypeError("Knowledge Base ingest receipt must be an object");
|
|
414
|
+
receipt = onlyReceipt;
|
|
415
|
+
}
|
|
416
|
+
const sourcePublicId = requiredString(receipt, "sourcePublicId");
|
|
417
|
+
return {
|
|
418
|
+
knowledgeBasePublicId: requiredString(receipt, "knowledgeBasePublicId"),
|
|
419
|
+
sourcePublicId,
|
|
420
|
+
sourceType: requiredString(receipt, "sourceType"),
|
|
421
|
+
status: normalizeSourceStatus(receipt.status),
|
|
422
|
+
pollToolName: "thorbit_kb_source_status",
|
|
423
|
+
pollInput: { sourcePublicIds: [sourcePublicId] }
|
|
424
|
+
};
|
|
425
|
+
}
|
|
426
|
+
function normalizeSuccessResult(toolName, value, envelopeUsage) {
|
|
427
|
+
const result = asRecord(value);
|
|
428
|
+
if (!result) throw new TypeError("Knowledge Base result must be an object");
|
|
429
|
+
switch (toolName) {
|
|
430
|
+
case "thorbit_kb_create":
|
|
431
|
+
return normalizeKnowledgeBase(asRecord(result.knowledgeBase) ?? result);
|
|
432
|
+
case "thorbit_kb_list": {
|
|
433
|
+
if (!Array.isArray(result.knowledgeBases)) {
|
|
434
|
+
throw new TypeError("Knowledge Base list is missing knowledgeBases");
|
|
435
|
+
}
|
|
436
|
+
return {
|
|
437
|
+
knowledgeBases: result.knowledgeBases.slice(0, 100).map(normalizeKnowledgeBase),
|
|
438
|
+
nextCursor: optionalString(result, "nextCursor")
|
|
439
|
+
};
|
|
440
|
+
}
|
|
441
|
+
case "thorbit_kb_source_status": {
|
|
442
|
+
let source = result;
|
|
443
|
+
if (Array.isArray(result.sources)) {
|
|
444
|
+
if (result.sources.length !== 1) {
|
|
445
|
+
throw new TypeError("The exact Knowledge Base source-status contract requires one provider source");
|
|
446
|
+
}
|
|
447
|
+
const onlySource = asRecord(result.sources[0]);
|
|
448
|
+
if (!onlySource) throw new TypeError("Knowledge Base source status must be an object");
|
|
449
|
+
source = onlySource;
|
|
450
|
+
}
|
|
451
|
+
const rawError = optionalString(source, "error") ?? optionalString(source, "errorMessage");
|
|
452
|
+
return {
|
|
453
|
+
knowledgeBasePublicId: requiredString(source, "knowledgeBasePublicId"),
|
|
454
|
+
sourcePublicId: requiredString(source, "sourcePublicId"),
|
|
455
|
+
sourceType: requiredString(source, "sourceType"),
|
|
456
|
+
status: normalizeSourceStatus(source.status),
|
|
457
|
+
progressPercent: requiredNumber(source, "progressPercent"),
|
|
458
|
+
error: rawError ? rawError.slice(0, 4e3) : null,
|
|
459
|
+
updatedAt: requiredDateTime(source, "updatedAt")
|
|
460
|
+
};
|
|
461
|
+
}
|
|
462
|
+
case "thorbit_kb_ingest_url":
|
|
463
|
+
case "thorbit_kb_ingest_site":
|
|
464
|
+
case "thorbit_kb_ingest_youtube":
|
|
465
|
+
case "thorbit_kb_ingest_text":
|
|
466
|
+
return normalizeIngestReceipt(result);
|
|
467
|
+
case "thorbit_kb_search": {
|
|
468
|
+
if (!Array.isArray(result.results)) {
|
|
469
|
+
throw new TypeError("Knowledge Base search is missing results");
|
|
470
|
+
}
|
|
471
|
+
return {
|
|
472
|
+
query: requiredString(result, "query"),
|
|
473
|
+
results: result.results.slice(0, 50).map((value2) => {
|
|
474
|
+
const match = asRecord(value2);
|
|
475
|
+
if (!match) throw new TypeError("Knowledge Base search match must be an object");
|
|
476
|
+
const text = typeof match.text === "string" ? match.text : requiredString(match, "content");
|
|
477
|
+
return {
|
|
478
|
+
chunkPublicId: requiredString(match, "chunkPublicId"),
|
|
479
|
+
text: text.slice(0, 5e4),
|
|
480
|
+
score: requiredNumber(match, "score")
|
|
481
|
+
};
|
|
482
|
+
}),
|
|
483
|
+
citations: normalizeCitationList(result.citations)
|
|
484
|
+
};
|
|
485
|
+
}
|
|
486
|
+
case "thorbit_kb_ask": {
|
|
487
|
+
const sufficiency = asRecord(result.sufficiency);
|
|
488
|
+
const followUpValue = Array.isArray(result.followUps) ? result.followUps : sufficiency?.followUpSuggestions;
|
|
489
|
+
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) : [];
|
|
490
|
+
const usage = asRecord(envelopeUsage);
|
|
491
|
+
const explicitModelId = optionalString(result, "modelId");
|
|
492
|
+
return {
|
|
493
|
+
answer: requiredString(result, "answer").slice(0, 5e5),
|
|
494
|
+
citations: normalizeCitationList(result.citations),
|
|
495
|
+
followUps,
|
|
496
|
+
modelId: explicitModelId !== null ? safeMetadataIdentifier(explicitModelId) : safeMetadataIdentifier(usage?.modelId)
|
|
497
|
+
};
|
|
498
|
+
}
|
|
499
|
+
}
|
|
500
|
+
}
|
|
501
|
+
function normalizeUsage(value) {
|
|
502
|
+
const usage = asRecord(value);
|
|
503
|
+
if (!usage) return void 0;
|
|
504
|
+
const output = {};
|
|
505
|
+
for (const key of ["creditsConsumed", "estimatedUsd"]) {
|
|
506
|
+
const candidate = usage[key];
|
|
507
|
+
if (typeof candidate === "number" && Number.isFinite(candidate) && candidate >= 0) {
|
|
508
|
+
output[key] = candidate;
|
|
509
|
+
}
|
|
510
|
+
}
|
|
511
|
+
for (const key of ["inputTokens", "outputTokens"]) {
|
|
512
|
+
const candidate = usage[key];
|
|
513
|
+
if (typeof candidate === "number" && Number.isInteger(candidate) && candidate >= 0) {
|
|
514
|
+
output[key] = candidate;
|
|
515
|
+
}
|
|
516
|
+
}
|
|
517
|
+
for (const key of ["provider", "modelId"]) {
|
|
518
|
+
const candidate = safeMetadataIdentifier(usage[key]);
|
|
519
|
+
if (candidate !== null) output[key] = candidate;
|
|
520
|
+
}
|
|
521
|
+
return Object.keys(output).length > 0 ? output : void 0;
|
|
522
|
+
}
|
|
523
|
+
function successNextActions(toolName, result) {
|
|
524
|
+
const record = asRecord(result);
|
|
525
|
+
if (!record) return [];
|
|
526
|
+
if (toolName.startsWith("thorbit_kb_ingest_")) {
|
|
527
|
+
return [{
|
|
528
|
+
toolName: "thorbit_kb_source_status",
|
|
529
|
+
reason: "Check the real provider-backed source status after ingestion.",
|
|
530
|
+
input: record.pollInput
|
|
531
|
+
}];
|
|
532
|
+
}
|
|
533
|
+
if (toolName === "thorbit_kb_source_status") {
|
|
534
|
+
if (record.status === "pending" || record.status === "processing") {
|
|
535
|
+
return [{
|
|
536
|
+
toolName: "thorbit_kb_source_status",
|
|
537
|
+
reason: "Poll this source until it is ready or failed.",
|
|
538
|
+
input: { sourcePublicIds: [record.sourcePublicId] }
|
|
539
|
+
}];
|
|
540
|
+
}
|
|
541
|
+
if (record.status === "ready") {
|
|
542
|
+
return [
|
|
543
|
+
{
|
|
544
|
+
toolName: "thorbit_kb_search",
|
|
545
|
+
reason: "Retrieve bounded citation-ready chunks from the ready knowledge base.",
|
|
546
|
+
input: { knowledgeBasePublicId: record.knowledgeBasePublicId }
|
|
547
|
+
},
|
|
548
|
+
{
|
|
549
|
+
toolName: "thorbit_kb_ask",
|
|
550
|
+
reason: "Ask a grounded question against the ready knowledge base.",
|
|
551
|
+
input: { knowledgeBasePublicId: record.knowledgeBasePublicId }
|
|
552
|
+
}
|
|
553
|
+
];
|
|
554
|
+
}
|
|
555
|
+
}
|
|
556
|
+
if (toolName === "thorbit_kb_search") {
|
|
557
|
+
return [{
|
|
558
|
+
toolName: "thorbit_kb_ask",
|
|
559
|
+
reason: "Synthesize a grounded answer when the retrieved chunks are sufficient.",
|
|
560
|
+
input: { question: record.query }
|
|
561
|
+
}];
|
|
562
|
+
}
|
|
563
|
+
return [];
|
|
564
|
+
}
|
|
565
|
+
function normalizedErrorCode(code) {
|
|
566
|
+
if (PUBLIC_ERROR_CODES.has(code)) return code;
|
|
567
|
+
if (code === "ingestion_error" || code === "invalid_response" || code.startsWith("http_")) {
|
|
568
|
+
return "provider_error";
|
|
569
|
+
}
|
|
570
|
+
return "internal_error";
|
|
571
|
+
}
|
|
572
|
+
function errorRecovery(toolName, code) {
|
|
573
|
+
const transient = code === "provider_error" || code === "rate_limited" || code === "internal_error";
|
|
574
|
+
if (!transient || !IDEMPOTENT_READ_TOOLS.has(toolName)) {
|
|
575
|
+
return { retryable: false, next: [] };
|
|
576
|
+
}
|
|
577
|
+
return {
|
|
578
|
+
retryable: true,
|
|
579
|
+
next: [{
|
|
580
|
+
toolName,
|
|
581
|
+
reason: code === "rate_limited" ? "Retry this idempotent read after the rate limit resets." : "Retry this idempotent read after the transient service issue is resolved."
|
|
582
|
+
}]
|
|
583
|
+
};
|
|
584
|
+
}
|
|
585
|
+
function projectionErrorDetails(error) {
|
|
586
|
+
const issueRecord = asRecord(error);
|
|
587
|
+
const issues = Array.isArray(issueRecord?.issues) ? issueRecord.issues.slice(0, 25).map((issue) => {
|
|
588
|
+
const issueValue = asRecord(issue);
|
|
589
|
+
return {
|
|
590
|
+
path: Array.isArray(issueValue?.path) ? issueValue.path.map(String).join(".") : "",
|
|
591
|
+
code: typeof issueValue?.code === "string" ? issueValue.code : "invalid_result"
|
|
592
|
+
};
|
|
593
|
+
}) : [];
|
|
594
|
+
return {
|
|
595
|
+
reason: "Hosted result did not satisfy the exact public Knowledge Base result contract.",
|
|
596
|
+
...issues.length > 0 ? { schemaIssues: issues } : {}
|
|
597
|
+
};
|
|
598
|
+
}
|
|
599
|
+
function successSummary(toolName, result) {
|
|
600
|
+
const record = asRecord(result);
|
|
601
|
+
switch (toolName) {
|
|
602
|
+
case "thorbit_kb_create":
|
|
603
|
+
return `Created Thorbit knowledge base ${String(record?.name ?? "")}.`;
|
|
604
|
+
case "thorbit_kb_list":
|
|
605
|
+
return `Found ${Array.isArray(record?.knowledgeBases) ? record.knowledgeBases.length : 0} Thorbit knowledge bases.`;
|
|
606
|
+
case "thorbit_kb_source_status":
|
|
607
|
+
return `Knowledge Base source ${String(record?.sourcePublicId ?? "")} is ${String(record?.status ?? "unknown")}.`;
|
|
608
|
+
case "thorbit_kb_ingest_url":
|
|
609
|
+
case "thorbit_kb_ingest_site":
|
|
610
|
+
case "thorbit_kb_ingest_youtube":
|
|
611
|
+
case "thorbit_kb_ingest_text":
|
|
612
|
+
return `Knowledge Base source ${String(record?.sourcePublicId ?? "")} was accepted with status ${String(record?.status ?? "unknown")}.`;
|
|
613
|
+
case "thorbit_kb_search":
|
|
614
|
+
return `Retrieved ${Array.isArray(record?.results) ? record.results.length : 0} bounded Knowledge Base chunks with citations.`;
|
|
615
|
+
case "thorbit_kb_ask":
|
|
616
|
+
return `Generated a grounded Knowledge Base answer with ${Array.isArray(record?.citations) ? record.citations.length : 0} citations.`;
|
|
617
|
+
}
|
|
618
|
+
}
|
|
619
|
+
function formatThorbitKbMcpToolResult(toolName, envelope, _requestInput) {
|
|
620
|
+
const requestId = safeText(envelope.requestId, "unavailable", 256);
|
|
621
|
+
const outputSchema = ThorbitKnowledgeBaseMcpToolStrictOutputSchemas[toolName];
|
|
622
|
+
if (!envelope.ok) {
|
|
623
|
+
const code = normalizedErrorCode(envelope.error.code);
|
|
624
|
+
const message = safeText(envelope.error.message, "Knowledge Base operation failed.");
|
|
625
|
+
const recovery = errorRecovery(toolName, code);
|
|
626
|
+
const structuredContent = outputSchema.parse({
|
|
627
|
+
ok: false,
|
|
628
|
+
toolName,
|
|
629
|
+
requestId,
|
|
630
|
+
error: {
|
|
631
|
+
code,
|
|
632
|
+
message,
|
|
633
|
+
retryable: recovery.retryable,
|
|
634
|
+
...envelope.error.details !== void 0 ? { details: safeDetails(envelope.error.details) } : {}
|
|
635
|
+
},
|
|
636
|
+
next: recovery.next
|
|
637
|
+
});
|
|
638
|
+
return {
|
|
639
|
+
content: [{ type: "text", text: `${message} Request ID: ${requestId}.` }],
|
|
640
|
+
structuredContent,
|
|
641
|
+
isError: true
|
|
642
|
+
};
|
|
643
|
+
}
|
|
644
|
+
try {
|
|
645
|
+
const result = normalizeSuccessResult(toolName, envelope.result, envelope.usage);
|
|
646
|
+
const summary = successSummary(toolName, result);
|
|
647
|
+
const usage = normalizeUsage(envelope.usage);
|
|
648
|
+
const structuredContent = outputSchema.parse({
|
|
649
|
+
ok: true,
|
|
650
|
+
toolName,
|
|
651
|
+
requestId,
|
|
652
|
+
summary,
|
|
653
|
+
result,
|
|
654
|
+
artifacts: [],
|
|
655
|
+
next: successNextActions(toolName, result),
|
|
656
|
+
warnings: (envelope.warnings ?? []).map((warning) => safeText(warning, "Hosted warning")),
|
|
657
|
+
...usage ? { usage } : {}
|
|
658
|
+
});
|
|
659
|
+
return {
|
|
660
|
+
content: [{ type: "text", text: summary }],
|
|
661
|
+
structuredContent,
|
|
662
|
+
isError: false
|
|
663
|
+
};
|
|
664
|
+
} catch (error) {
|
|
665
|
+
const message = "Thorbit completed the Knowledge Base operation, but its hosted result could not be projected to the exact public contract.";
|
|
666
|
+
const structuredContent = outputSchema.parse({
|
|
667
|
+
ok: false,
|
|
668
|
+
toolName,
|
|
669
|
+
requestId,
|
|
670
|
+
error: {
|
|
671
|
+
code: "provider_error",
|
|
672
|
+
message,
|
|
673
|
+
retryable: false,
|
|
674
|
+
details: projectionErrorDetails(error)
|
|
675
|
+
},
|
|
676
|
+
next: []
|
|
677
|
+
});
|
|
678
|
+
return {
|
|
679
|
+
content: [{ type: "text", text: `${message} Request ID: ${requestId}.` }],
|
|
680
|
+
structuredContent,
|
|
681
|
+
isError: true
|
|
682
|
+
};
|
|
683
|
+
}
|
|
684
|
+
}
|
|
685
|
+
|
|
686
|
+
// src/thorbit-kb-mcp-tool-names.ts
|
|
687
|
+
var ThorbitKnowledgeBaseMcpToolNames = [
|
|
688
|
+
"thorbit_kb_create",
|
|
689
|
+
"thorbit_kb_list",
|
|
690
|
+
"thorbit_kb_source_status",
|
|
691
|
+
"thorbit_kb_ingest_url",
|
|
692
|
+
"thorbit_kb_ingest_site",
|
|
693
|
+
"thorbit_kb_ingest_youtube",
|
|
694
|
+
"thorbit_kb_ingest_text",
|
|
695
|
+
"thorbit_kb_search",
|
|
696
|
+
"thorbit_kb_ask"
|
|
697
|
+
];
|
|
149
698
|
|
|
150
699
|
// src/thorbit-kb-mcp-server.ts
|
|
151
|
-
var VERSION = "0.2.
|
|
152
|
-
function readOnlyAnnotations(title, idempotent = true) {
|
|
700
|
+
var VERSION = "0.2.9";
|
|
701
|
+
function readOnlyAnnotations(title, idempotent = true, openWorldHint = false) {
|
|
153
702
|
return {
|
|
154
703
|
title,
|
|
155
704
|
readOnlyHint: true,
|
|
156
705
|
destructiveHint: false,
|
|
157
706
|
idempotentHint: idempotent,
|
|
158
|
-
openWorldHint
|
|
707
|
+
openWorldHint
|
|
159
708
|
};
|
|
160
709
|
}
|
|
161
710
|
function ingestAnnotations(title, openWorldHint) {
|
|
@@ -167,6 +716,101 @@ function ingestAnnotations(title, openWorldHint) {
|
|
|
167
716
|
openWorldHint
|
|
168
717
|
};
|
|
169
718
|
}
|
|
719
|
+
function defineKnowledgeBaseQuality(quality) {
|
|
720
|
+
return ThorbitMcpToolQualityMetadataSchema.parse({ productId: "kb", ...quality });
|
|
721
|
+
}
|
|
722
|
+
var KNOWLEDGE_BASE_TOOL_QUALITY = {
|
|
723
|
+
thorbit_kb_create: defineKnowledgeBaseQuality({
|
|
724
|
+
requiredScopes: ["knowledge_base:ingest"],
|
|
725
|
+
whenToUse: ["Use to create a new caller-organization or project Knowledge Base."],
|
|
726
|
+
avoidWhen: ["Avoid when a suitable Knowledge Base already exists; list first."],
|
|
727
|
+
userPhrases: ["create a knowledge base", "make a RAG library", "start a KB"],
|
|
728
|
+
costSummary: "Low-cost durable Knowledge Base record creation.",
|
|
729
|
+
resultMode: "inline",
|
|
730
|
+
nextTools: ["thorbit_kb_ingest_url", "thorbit_kb_ingest_text"],
|
|
731
|
+
sideEffects: ["Creates a durable caller-organization Knowledge Base."]
|
|
732
|
+
}),
|
|
733
|
+
thorbit_kb_list: defineKnowledgeBaseQuality({
|
|
734
|
+
requiredScopes: ["knowledge_base:read"],
|
|
735
|
+
whenToUse: ["Use to find a visible Knowledge Base public ID before ingestion or retrieval."],
|
|
736
|
+
avoidWhen: ["Avoid when the exact Knowledge Base public ID is already known."],
|
|
737
|
+
userPhrases: ["list knowledge bases", "find my KB", "show RAG libraries"],
|
|
738
|
+
costSummary: "Low-cost caller-organization database read.",
|
|
739
|
+
resultMode: "paginated",
|
|
740
|
+
nextTools: ["thorbit_kb_search", "thorbit_kb_ask"],
|
|
741
|
+
sideEffects: []
|
|
742
|
+
}),
|
|
743
|
+
thorbit_kb_source_status: defineKnowledgeBaseQuality({
|
|
744
|
+
requiredScopes: ["knowledge_base:read"],
|
|
745
|
+
whenToUse: ["Use to poll one provider-backed source receipt returned by ingestion."],
|
|
746
|
+
avoidWhen: ["Avoid for retrieving chunks or synthesizing an answer."],
|
|
747
|
+
userPhrases: ["check ingest status", "is this source ready", "poll KB source"],
|
|
748
|
+
costSummary: "Low-cost caller-organization source status read.",
|
|
749
|
+
resultMode: "async",
|
|
750
|
+
nextTools: ["thorbit_kb_search", "thorbit_kb_ask"],
|
|
751
|
+
sideEffects: []
|
|
752
|
+
}),
|
|
753
|
+
thorbit_kb_ingest_url: defineKnowledgeBaseQuality({
|
|
754
|
+
requiredScopes: ["knowledge_base:ingest"],
|
|
755
|
+
whenToUse: ["Use to extract and ingest one public URL into a known Knowledge Base."],
|
|
756
|
+
avoidWhen: ["Avoid for whole websites, YouTube videos, or content already in hand."],
|
|
757
|
+
userPhrases: ["ingest this URL", "add this page to the KB", "vectorize this web page"],
|
|
758
|
+
costSummary: "External MCP Scraper extraction plus durable chunking and vectorization.",
|
|
759
|
+
resultMode: "async",
|
|
760
|
+
nextTools: ["thorbit_kb_source_status"],
|
|
761
|
+
sideEffects: ["Creates an append-only durable Knowledge Base source and chunks."]
|
|
762
|
+
}),
|
|
763
|
+
thorbit_kb_ingest_site: defineKnowledgeBaseQuality({
|
|
764
|
+
requiredScopes: ["knowledge_base:ingest"],
|
|
765
|
+
whenToUse: ["Use to map and ingest a bounded set of pages from one website."],
|
|
766
|
+
avoidWhen: ["Avoid for one known URL, which is cheaper through URL ingestion."],
|
|
767
|
+
userPhrases: ["ingest this website", "crawl pages into the KB", "build a KB from this site"],
|
|
768
|
+
costSummary: "Bounded MCP Scraper mapping and extraction plus durable vectorization per page.",
|
|
769
|
+
resultMode: "async",
|
|
770
|
+
nextTools: ["thorbit_kb_source_status"],
|
|
771
|
+
sideEffects: ["Creates append-only Knowledge Base sources and chunks for accepted pages."]
|
|
772
|
+
}),
|
|
773
|
+
thorbit_kb_ingest_youtube: defineKnowledgeBaseQuality({
|
|
774
|
+
requiredScopes: ["knowledge_base:ingest"],
|
|
775
|
+
whenToUse: ["Use to transcribe and ingest one YouTube video into a known Knowledge Base."],
|
|
776
|
+
avoidWhen: ["Avoid for web pages or caller-supplied text."],
|
|
777
|
+
userPhrases: ["ingest this YouTube video", "add this transcript to the KB", "vectorize this video"],
|
|
778
|
+
costSummary: "External transcription plus durable chunking and vectorization.",
|
|
779
|
+
resultMode: "async",
|
|
780
|
+
nextTools: ["thorbit_kb_source_status"],
|
|
781
|
+
sideEffects: ["Creates an append-only durable transcript source and chunks."]
|
|
782
|
+
}),
|
|
783
|
+
thorbit_kb_ingest_text: defineKnowledgeBaseQuality({
|
|
784
|
+
requiredScopes: ["knowledge_base:ingest"],
|
|
785
|
+
whenToUse: ["Use to ingest text or Markdown already supplied by the caller."],
|
|
786
|
+
avoidWhen: ["Avoid when Thorbit must fetch a URL, website, or YouTube transcript."],
|
|
787
|
+
userPhrases: ["ingest this text", "add these notes to the KB", "vectorize this Markdown"],
|
|
788
|
+
costSummary: "Durable chunking and vectorization without external scraping.",
|
|
789
|
+
resultMode: "async",
|
|
790
|
+
nextTools: ["thorbit_kb_source_status"],
|
|
791
|
+
sideEffects: ["Creates an append-only durable Knowledge Base source and chunks."]
|
|
792
|
+
}),
|
|
793
|
+
thorbit_kb_search: defineKnowledgeBaseQuality({
|
|
794
|
+
requiredScopes: ["knowledge_base:read"],
|
|
795
|
+
whenToUse: ["Use to retrieve bounded citation-ready chunks without answer synthesis."],
|
|
796
|
+
avoidWhen: ["Avoid when the caller wants a direct grounded answer."],
|
|
797
|
+
userPhrases: ["search the KB", "retrieve source chunks", "find citation evidence"],
|
|
798
|
+
costSummary: "Bounded vector or hybrid retrieval and optional reranking.",
|
|
799
|
+
resultMode: "inline",
|
|
800
|
+
nextTools: ["thorbit_kb_ask"],
|
|
801
|
+
sideEffects: []
|
|
802
|
+
}),
|
|
803
|
+
thorbit_kb_ask: defineKnowledgeBaseQuality({
|
|
804
|
+
requiredScopes: ["knowledge_base:read", "knowledge_base:ask"],
|
|
805
|
+
whenToUse: ["Use to synthesize a direct answer grounded in bounded Knowledge Base citations."],
|
|
806
|
+
avoidWhen: ["Avoid when raw retrieved passages are required for caller-side reasoning."],
|
|
807
|
+
userPhrases: ["ask the knowledge base", "answer from my KB", "give me a cited answer"],
|
|
808
|
+
costSummary: "Bounded retrieval plus potentially metered model answer generation.",
|
|
809
|
+
resultMode: "inline",
|
|
810
|
+
nextTools: ["thorbit_kb_search"],
|
|
811
|
+
sideEffects: []
|
|
812
|
+
})
|
|
813
|
+
};
|
|
170
814
|
var SERVER_INSTRUCTIONS = [
|
|
171
815
|
"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.",
|
|
172
816
|
"",
|
|
@@ -186,9 +830,7 @@ var SERVER_INSTRUCTIONS = [
|
|
|
186
830
|
"- Need citation-ready chunks yourself, not a synthesized answer -> **thorbit_kb_search**.",
|
|
187
831
|
'- 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.'
|
|
188
832
|
].join("\n");
|
|
189
|
-
function
|
|
190
|
-
const callTool = (toolName, input) => options.callTool(toolName, input);
|
|
191
|
-
const server = new McpServer({ name: "thorbit-kb-mcp", version: VERSION }, { instructions: SERVER_INSTRUCTIONS });
|
|
833
|
+
function registerThorbitKnowledgeBaseResources(server, callTool) {
|
|
192
834
|
server.registerResource(
|
|
193
835
|
"knowledge-bases",
|
|
194
836
|
"thorbit-kb://knowledge-bases",
|
|
@@ -212,114 +854,120 @@ function buildThorbitKnowledgeBaseMcpServer(options) {
|
|
|
212
854
|
},
|
|
213
855
|
async (uri, variables) => {
|
|
214
856
|
const sourcePublicId = Array.isArray(variables.sourcePublicId) ? variables.sourcePublicId[0] : variables.sourcePublicId;
|
|
215
|
-
const envelope = await callTool("thorbit_kb_source_status", {
|
|
857
|
+
const envelope = await callTool("thorbit_kb_source_status", {
|
|
858
|
+
sourcePublicIds: [String(sourcePublicId)]
|
|
859
|
+
});
|
|
216
860
|
return { contents: [{ uri: uri.href, mimeType: "application/json", text: JSON.stringify(envelope, null, 2) }] };
|
|
217
861
|
}
|
|
218
862
|
);
|
|
863
|
+
}
|
|
864
|
+
function registerThorbitKnowledgeBaseMcpTools(server, callTool) {
|
|
219
865
|
function registerTool(toolName, config) {
|
|
220
|
-
server.registerTool(toolName,
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
866
|
+
server.registerTool(toolName, {
|
|
867
|
+
title: config.title,
|
|
868
|
+
description: config.description,
|
|
869
|
+
inputSchema: config.inputSchema,
|
|
870
|
+
outputSchema: config.outputSchema,
|
|
871
|
+
annotations: config.annotations,
|
|
872
|
+
_meta: { thorbit: config.quality }
|
|
873
|
+
}, async (input) => formatThorbitKbMcpToolResult(
|
|
874
|
+
toolName,
|
|
875
|
+
await callTool(toolName, input),
|
|
876
|
+
input
|
|
877
|
+
));
|
|
224
878
|
}
|
|
225
879
|
registerTool("thorbit_kb_create", {
|
|
226
880
|
title: "Create Thorbit Knowledge Base",
|
|
227
881
|
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.",
|
|
228
882
|
inputSchema: ThorbitKbCreateInputSchema,
|
|
229
|
-
|
|
883
|
+
outputSchema: ThorbitKnowledgeBaseMcpToolOutputSchemas.thorbit_kb_create,
|
|
884
|
+
annotations: ingestAnnotations("Create Thorbit Knowledge Base", false),
|
|
885
|
+
quality: KNOWLEDGE_BASE_TOOL_QUALITY.thorbit_kb_create
|
|
230
886
|
});
|
|
231
887
|
registerTool("thorbit_kb_list", {
|
|
232
888
|
title: "List Thorbit Knowledge Bases",
|
|
233
889
|
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).",
|
|
234
890
|
inputSchema: ThorbitKbListInputSchema,
|
|
235
|
-
|
|
891
|
+
outputSchema: ThorbitKnowledgeBaseMcpToolOutputSchemas.thorbit_kb_list,
|
|
892
|
+
annotations: readOnlyAnnotations("List Thorbit Knowledge Bases"),
|
|
893
|
+
quality: KNOWLEDGE_BASE_TOOL_QUALITY.thorbit_kb_list
|
|
236
894
|
});
|
|
237
895
|
registerTool("thorbit_kb_source_status", {
|
|
238
896
|
title: "Read Thorbit KB Source Status",
|
|
239
|
-
description: "Poll ingestion status for source public
|
|
897
|
+
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.",
|
|
240
898
|
inputSchema: ThorbitKbSourceStatusInputSchema,
|
|
241
|
-
|
|
899
|
+
outputSchema: ThorbitKnowledgeBaseMcpToolOutputSchemas.thorbit_kb_source_status,
|
|
900
|
+
annotations: readOnlyAnnotations("Read Thorbit KB Source Status"),
|
|
901
|
+
quality: KNOWLEDGE_BASE_TOOL_QUALITY.thorbit_kb_source_status
|
|
242
902
|
});
|
|
243
903
|
registerTool("thorbit_kb_ingest_url", {
|
|
244
904
|
title: "Ingest URL Into Thorbit KB",
|
|
245
|
-
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
|
|
905
|
+
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.",
|
|
246
906
|
inputSchema: ThorbitKbIngestUrlInputSchema,
|
|
247
|
-
|
|
907
|
+
outputSchema: ThorbitKnowledgeBaseMcpToolOutputSchemas.thorbit_kb_ingest_url,
|
|
908
|
+
annotations: ingestAnnotations("Ingest URL Into Thorbit KB", true),
|
|
909
|
+
quality: KNOWLEDGE_BASE_TOOL_QUALITY.thorbit_kb_ingest_url
|
|
248
910
|
});
|
|
249
911
|
registerTool("thorbit_kb_ingest_site", {
|
|
250
912
|
title: "Ingest Website Into Thorbit KB",
|
|
251
|
-
description: "Map a website through MCP Scraper, extract selected pages (up to 100, default 25
|
|
913
|
+
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.",
|
|
252
914
|
inputSchema: ThorbitKbIngestSiteInputSchema,
|
|
253
|
-
|
|
915
|
+
outputSchema: ThorbitKnowledgeBaseMcpToolOutputSchemas.thorbit_kb_ingest_site,
|
|
916
|
+
annotations: ingestAnnotations("Ingest Website Into Thorbit KB", true),
|
|
917
|
+
quality: KNOWLEDGE_BASE_TOOL_QUALITY.thorbit_kb_ingest_site
|
|
254
918
|
});
|
|
255
919
|
registerTool("thorbit_kb_ingest_youtube", {
|
|
256
920
|
title: "Ingest YouTube Into Thorbit KB",
|
|
257
|
-
description: "Transcribe
|
|
921
|
+
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.",
|
|
258
922
|
inputSchema: ThorbitKbIngestYoutubeInputSchema,
|
|
259
|
-
|
|
923
|
+
outputSchema: ThorbitKnowledgeBaseMcpToolOutputSchemas.thorbit_kb_ingest_youtube,
|
|
924
|
+
annotations: ingestAnnotations("Ingest YouTube Into Thorbit KB", true),
|
|
925
|
+
quality: KNOWLEDGE_BASE_TOOL_QUALITY.thorbit_kb_ingest_youtube
|
|
260
926
|
});
|
|
261
927
|
registerTool("thorbit_kb_ingest_text", {
|
|
262
928
|
title: "Ingest Text Into Thorbit KB",
|
|
263
|
-
description: "Submit text or Markdown
|
|
929
|
+
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.",
|
|
264
930
|
inputSchema: ThorbitKbIngestTextInputSchema,
|
|
265
|
-
|
|
931
|
+
outputSchema: ThorbitKnowledgeBaseMcpToolOutputSchemas.thorbit_kb_ingest_text,
|
|
932
|
+
annotations: ingestAnnotations("Ingest Text Into Thorbit KB", false),
|
|
933
|
+
quality: KNOWLEDGE_BASE_TOOL_QUALITY.thorbit_kb_ingest_text
|
|
266
934
|
});
|
|
267
935
|
registerTool("thorbit_kb_search", {
|
|
268
936
|
title: "Search Thorbit Knowledge Base",
|
|
269
|
-
description: "Search knowledge-base content and
|
|
937
|
+
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.",
|
|
270
938
|
inputSchema: ThorbitKbSearchInputSchema,
|
|
271
|
-
|
|
939
|
+
outputSchema: ThorbitKnowledgeBaseMcpToolOutputSchemas.thorbit_kb_search,
|
|
940
|
+
annotations: readOnlyAnnotations("Search Thorbit Knowledge Base", true, true),
|
|
941
|
+
quality: KNOWLEDGE_BASE_TOOL_QUALITY.thorbit_kb_search
|
|
272
942
|
});
|
|
273
943
|
registerTool("thorbit_kb_ask", {
|
|
274
944
|
title: "Ask Thorbit Knowledge Base",
|
|
275
|
-
description:
|
|
945
|
+
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.",
|
|
276
946
|
inputSchema: ThorbitKbAskInputSchema,
|
|
277
|
-
|
|
947
|
+
outputSchema: ThorbitKnowledgeBaseMcpToolOutputSchemas.thorbit_kb_ask,
|
|
948
|
+
annotations: readOnlyAnnotations("Ask Thorbit Knowledge Base", false, true),
|
|
949
|
+
quality: KNOWLEDGE_BASE_TOOL_QUALITY.thorbit_kb_ask
|
|
278
950
|
});
|
|
279
|
-
return server;
|
|
280
951
|
}
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
function readApiKeyFile() {
|
|
287
|
-
const explicitPath = process.env.THORBIT_KB_MCP_KEY_PATH?.trim();
|
|
288
|
-
const paths = [explicitPath, join(homedir(), ".thorbit-kb-mcp-key")].filter(Boolean);
|
|
289
|
-
for (const path of paths) {
|
|
290
|
-
try {
|
|
291
|
-
const value = readFileSync(path, "utf8").trim();
|
|
292
|
-
if (value) return value;
|
|
293
|
-
} catch {
|
|
294
|
-
continue;
|
|
295
|
-
}
|
|
296
|
-
}
|
|
297
|
-
return void 0;
|
|
298
|
-
}
|
|
299
|
-
function resolveThorbitKbMcpEnv() {
|
|
300
|
-
const apiKey = (process.env.THORBIT_API_KEY || process.env.THORBIT_MCP_API_KEY || process.env.THORBIT_KB_MCP_API_KEY || readApiKeyFile())?.trim();
|
|
301
|
-
if (!apiKey) {
|
|
302
|
-
throw new Error("THORBIT_API_KEY, THORBIT_MCP_API_KEY, or ~/.thorbit-kb-mcp-key is required");
|
|
952
|
+
var ThorbitKnowledgeBaseMcpToolRegistrar = class {
|
|
953
|
+
productId = "kb";
|
|
954
|
+
toolNames = ThorbitKnowledgeBaseMcpToolNames;
|
|
955
|
+
registerTools(server, callTool) {
|
|
956
|
+
registerThorbitKnowledgeBaseMcpTools(server, callTool);
|
|
303
957
|
}
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
958
|
+
};
|
|
959
|
+
function buildThorbitKnowledgeBaseMcpServer(options) {
|
|
960
|
+
const callTool = (toolName, input) => options.callTool(toolName, input);
|
|
961
|
+
const server = new McpServer(
|
|
962
|
+
{ name: "thorbit-kb-mcp", version: VERSION },
|
|
963
|
+
{ instructions: SERVER_INSTRUCTIONS }
|
|
964
|
+
);
|
|
965
|
+
registerThorbitKnowledgeBaseResources(server, callTool);
|
|
966
|
+
registerThorbitKnowledgeBaseMcpTools(server, callTool);
|
|
967
|
+
return server;
|
|
308
968
|
}
|
|
309
|
-
|
|
310
|
-
// src/thorbit-kb-mcp-tool-names.ts
|
|
311
|
-
var ThorbitKnowledgeBaseMcpToolNames = [
|
|
312
|
-
"thorbit_kb_create",
|
|
313
|
-
"thorbit_kb_list",
|
|
314
|
-
"thorbit_kb_source_status",
|
|
315
|
-
"thorbit_kb_ingest_url",
|
|
316
|
-
"thorbit_kb_ingest_site",
|
|
317
|
-
"thorbit_kb_ingest_youtube",
|
|
318
|
-
"thorbit_kb_ingest_text",
|
|
319
|
-
"thorbit_kb_search",
|
|
320
|
-
"thorbit_kb_ask"
|
|
321
|
-
];
|
|
322
969
|
export {
|
|
970
|
+
SERVER_INSTRUCTIONS,
|
|
323
971
|
ThorbitKbAskInputSchema,
|
|
324
972
|
ThorbitKbCreateInputSchema,
|
|
325
973
|
ThorbitKbIngestSiteInputSchema,
|
|
@@ -329,10 +977,22 @@ export {
|
|
|
329
977
|
ThorbitKbListInputSchema,
|
|
330
978
|
ThorbitKbSearchInputSchema,
|
|
331
979
|
ThorbitKbSourceStatusInputSchema,
|
|
980
|
+
ThorbitKnowledgeBaseAnswerResultSchema,
|
|
332
981
|
ThorbitKnowledgeBaseApiClient,
|
|
982
|
+
ThorbitKnowledgeBaseCitationSchema,
|
|
983
|
+
ThorbitKnowledgeBaseIngestResultSchema,
|
|
984
|
+
ThorbitKnowledgeBaseListResultSchema,
|
|
333
985
|
ThorbitKnowledgeBaseMcpToolInputSchemas,
|
|
334
986
|
ThorbitKnowledgeBaseMcpToolNames,
|
|
987
|
+
ThorbitKnowledgeBaseMcpToolOutputSchemas,
|
|
988
|
+
ThorbitKnowledgeBaseMcpToolRegistrar,
|
|
989
|
+
ThorbitKnowledgeBaseMcpToolResultSchemas,
|
|
990
|
+
ThorbitKnowledgeBaseMcpToolStrictOutputSchemas,
|
|
991
|
+
ThorbitKnowledgeBaseResultSchema,
|
|
992
|
+
ThorbitKnowledgeBaseSearchResultSchema,
|
|
993
|
+
ThorbitKnowledgeBaseSourceStatusResultSchema,
|
|
335
994
|
buildThorbitKnowledgeBaseMcpServer,
|
|
995
|
+
registerThorbitKnowledgeBaseMcpTools,
|
|
336
996
|
resolveThorbitKbMcpEnv
|
|
337
997
|
};
|
|
338
998
|
//# sourceMappingURL=index.js.map
|