@productbrain/mcp 0.0.1-beta.0
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/.env.mcp.example +32 -0
- package/README.md +238 -0
- package/dist/chunk-DGUM43GV.js +11 -0
- package/dist/chunk-DGUM43GV.js.map +1 -0
- package/dist/cli/index.js +11 -0
- package/dist/cli/index.js.map +1 -0
- package/dist/index.js +2546 -0
- package/dist/index.js.map +1 -0
- package/dist/setup-K757L5KR.js +227 -0
- package/dist/setup-K757L5KR.js.map +1 -0
- package/package.json +59 -0
package/dist/index.js
ADDED
|
@@ -0,0 +1,2546 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import "./chunk-DGUM43GV.js";
|
|
3
|
+
|
|
4
|
+
// src/index.ts
|
|
5
|
+
import { readFileSync as readFileSync2 } from "fs";
|
|
6
|
+
import { resolve as resolve2 } from "path";
|
|
7
|
+
import { McpServer as McpServer2 } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
8
|
+
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
|
9
|
+
|
|
10
|
+
// src/tools/knowledge.ts
|
|
11
|
+
import { z } from "zod";
|
|
12
|
+
|
|
13
|
+
// src/analytics.ts
|
|
14
|
+
import { userInfo } from "os";
|
|
15
|
+
import { PostHog } from "posthog-node";
|
|
16
|
+
var client = null;
|
|
17
|
+
var distinctId = "anonymous";
|
|
18
|
+
var POSTHOG_HOST = "https://eu.i.posthog.com";
|
|
19
|
+
function log(msg) {
|
|
20
|
+
if (process.env.MCP_DEBUG === "1") {
|
|
21
|
+
process.stderr.write(msg);
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
function initAnalytics() {
|
|
25
|
+
const apiKey = process.env.POSTHOG_MCP_KEY;
|
|
26
|
+
if (!apiKey) {
|
|
27
|
+
log("[MCP-ANALYTICS] POSTHOG_MCP_KEY not set \u2014 tracking disabled\n");
|
|
28
|
+
return;
|
|
29
|
+
}
|
|
30
|
+
client = new PostHog(apiKey, {
|
|
31
|
+
host: POSTHOG_HOST,
|
|
32
|
+
flushAt: 1,
|
|
33
|
+
flushInterval: 5e3
|
|
34
|
+
});
|
|
35
|
+
distinctId = process.env.MCP_USER_ID || fallbackDistinctId();
|
|
36
|
+
log(`[MCP-ANALYTICS] Initialized \u2014 host=${POSTHOG_HOST} distinctId=${distinctId}
|
|
37
|
+
`);
|
|
38
|
+
}
|
|
39
|
+
function fallbackDistinctId() {
|
|
40
|
+
try {
|
|
41
|
+
return userInfo().username;
|
|
42
|
+
} catch {
|
|
43
|
+
return `os-${process.pid}`;
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
function trackSessionStarted(workspaceSlug, workspaceId2, serverVersion) {
|
|
47
|
+
if (!client) return;
|
|
48
|
+
client.capture({
|
|
49
|
+
distinctId,
|
|
50
|
+
event: "mcp_session_started",
|
|
51
|
+
properties: {
|
|
52
|
+
workspace_slug: workspaceSlug,
|
|
53
|
+
workspace_id: workspaceId2,
|
|
54
|
+
server_version: serverVersion,
|
|
55
|
+
source: "mcp-server",
|
|
56
|
+
$groups: { workspace: workspaceId2 }
|
|
57
|
+
}
|
|
58
|
+
});
|
|
59
|
+
}
|
|
60
|
+
function trackToolCall(fn, status, durationMs, workspaceId2, errorMsg) {
|
|
61
|
+
const properties = {
|
|
62
|
+
tool: fn,
|
|
63
|
+
status,
|
|
64
|
+
duration_ms: durationMs,
|
|
65
|
+
workspace_slug: process.env.WORKSPACE_SLUG ?? "unknown",
|
|
66
|
+
source: "mcp-server",
|
|
67
|
+
$groups: { workspace: workspaceId2 }
|
|
68
|
+
};
|
|
69
|
+
if (errorMsg) properties.error = errorMsg;
|
|
70
|
+
if (!client) return;
|
|
71
|
+
client.capture({
|
|
72
|
+
distinctId,
|
|
73
|
+
event: "mcp_tool_called",
|
|
74
|
+
properties
|
|
75
|
+
});
|
|
76
|
+
}
|
|
77
|
+
async function shutdownAnalytics() {
|
|
78
|
+
await client?.shutdown();
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
// src/client.ts
|
|
82
|
+
var DEFAULT_CLOUD_URL = "https://earnest-sheep-635.convex.site";
|
|
83
|
+
var cachedWorkspaceId = null;
|
|
84
|
+
var cloudMode = false;
|
|
85
|
+
var AUDIT_BUFFER_SIZE = 50;
|
|
86
|
+
var auditBuffer = [];
|
|
87
|
+
function bootstrapCloudMode() {
|
|
88
|
+
const pbKey = process.env.PRODUCTBRAIN_API_KEY;
|
|
89
|
+
if (pbKey?.startsWith("pb_sk_")) {
|
|
90
|
+
const cloudUrl = process.env.PRODUCTBRAIN_URL ?? DEFAULT_CLOUD_URL;
|
|
91
|
+
process.env.CONVEX_SITE_URL ??= cloudUrl;
|
|
92
|
+
process.env.MCP_API_KEY ??= pbKey;
|
|
93
|
+
cloudMode = true;
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
function getEnv(key) {
|
|
97
|
+
const value = process.env[key];
|
|
98
|
+
if (!value) throw new Error(`${key} environment variable is required`);
|
|
99
|
+
return value;
|
|
100
|
+
}
|
|
101
|
+
function shouldLogAudit(status) {
|
|
102
|
+
return status === "error" || process.env.MCP_DEBUG === "1";
|
|
103
|
+
}
|
|
104
|
+
function audit(fn, status, durationMs, errorMsg) {
|
|
105
|
+
const ts = (/* @__PURE__ */ new Date()).toISOString();
|
|
106
|
+
const workspace = cachedWorkspaceId ?? "unresolved";
|
|
107
|
+
const entry = { ts, fn, workspace, status, durationMs };
|
|
108
|
+
if (errorMsg) entry.error = errorMsg;
|
|
109
|
+
auditBuffer.push(entry);
|
|
110
|
+
if (auditBuffer.length > AUDIT_BUFFER_SIZE) auditBuffer.shift();
|
|
111
|
+
trackToolCall(fn, status, durationMs, workspace, errorMsg);
|
|
112
|
+
if (!shouldLogAudit(status)) return;
|
|
113
|
+
const base = `[MCP-AUDIT] ${ts} fn=${fn} workspace=${workspace} status=${status} duration=${durationMs}ms`;
|
|
114
|
+
if (status === "error" && errorMsg) {
|
|
115
|
+
process.stderr.write(`${base} error=${JSON.stringify(errorMsg)}
|
|
116
|
+
`);
|
|
117
|
+
} else {
|
|
118
|
+
process.stderr.write(`${base}
|
|
119
|
+
`);
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
function getAuditLog() {
|
|
123
|
+
return auditBuffer;
|
|
124
|
+
}
|
|
125
|
+
async function mcpCall(fn, args = {}) {
|
|
126
|
+
const siteUrl = getEnv("CONVEX_SITE_URL").replace(/\/$/, "");
|
|
127
|
+
const apiKey = getEnv("MCP_API_KEY");
|
|
128
|
+
const start = Date.now();
|
|
129
|
+
let res;
|
|
130
|
+
try {
|
|
131
|
+
res = await fetch(`${siteUrl}/api/mcp`, {
|
|
132
|
+
method: "POST",
|
|
133
|
+
headers: {
|
|
134
|
+
"Content-Type": "application/json",
|
|
135
|
+
Authorization: `Bearer ${apiKey}`
|
|
136
|
+
},
|
|
137
|
+
body: JSON.stringify({ fn, args })
|
|
138
|
+
});
|
|
139
|
+
} catch (err) {
|
|
140
|
+
audit(fn, "error", Date.now() - start, err.message);
|
|
141
|
+
throw new Error(`MCP call "${fn}" network error: ${err.message}`);
|
|
142
|
+
}
|
|
143
|
+
const json = await res.json();
|
|
144
|
+
if (!res.ok || json.error) {
|
|
145
|
+
audit(fn, "error", Date.now() - start, json.error);
|
|
146
|
+
throw new Error(`MCP call "${fn}" failed (${res.status}): ${json.error ?? "unknown error"}`);
|
|
147
|
+
}
|
|
148
|
+
audit(fn, "ok", Date.now() - start);
|
|
149
|
+
return json.data;
|
|
150
|
+
}
|
|
151
|
+
async function getWorkspaceId() {
|
|
152
|
+
if (cachedWorkspaceId) return cachedWorkspaceId;
|
|
153
|
+
if (cloudMode) {
|
|
154
|
+
const workspace2 = await mcpCall(
|
|
155
|
+
"resolveWorkspace",
|
|
156
|
+
{ slug: "__cloud__" }
|
|
157
|
+
);
|
|
158
|
+
if (!workspace2) {
|
|
159
|
+
throw new Error("Cloud key is valid but no workspace is associated. Run `npx productbrain setup` again.");
|
|
160
|
+
}
|
|
161
|
+
cachedWorkspaceId = workspace2._id;
|
|
162
|
+
return cachedWorkspaceId;
|
|
163
|
+
}
|
|
164
|
+
const slug = getEnv("WORKSPACE_SLUG");
|
|
165
|
+
const workspace = await mcpCall(
|
|
166
|
+
"resolveWorkspace",
|
|
167
|
+
{ slug }
|
|
168
|
+
);
|
|
169
|
+
if (!workspace) {
|
|
170
|
+
throw new Error(`Workspace with slug "${slug}" not found`);
|
|
171
|
+
}
|
|
172
|
+
cachedWorkspaceId = workspace._id;
|
|
173
|
+
return cachedWorkspaceId;
|
|
174
|
+
}
|
|
175
|
+
async function mcpQuery(fn, args = {}) {
|
|
176
|
+
const workspaceId2 = await getWorkspaceId();
|
|
177
|
+
return mcpCall(fn, { ...args, workspaceId: workspaceId2 });
|
|
178
|
+
}
|
|
179
|
+
async function mcpMutation(fn, args = {}) {
|
|
180
|
+
const workspaceId2 = await getWorkspaceId();
|
|
181
|
+
return mcpCall(fn, { ...args, workspaceId: workspaceId2 });
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
// src/tools/knowledge.ts
|
|
185
|
+
function extractPreview(data, maxLen) {
|
|
186
|
+
if (!data || typeof data !== "object") return "";
|
|
187
|
+
const raw = data.description ?? data.canonical ?? data.detail ?? "";
|
|
188
|
+
if (typeof raw !== "string" || !raw) return "";
|
|
189
|
+
return raw.length > maxLen ? raw.substring(0, maxLen) + "..." : raw;
|
|
190
|
+
}
|
|
191
|
+
function registerKnowledgeTools(server2) {
|
|
192
|
+
server2.registerTool(
|
|
193
|
+
"list-collections",
|
|
194
|
+
{
|
|
195
|
+
title: "Browse Collections",
|
|
196
|
+
description: "List every knowledge collection in the workspace \u2014 glossary, business rules, tracking events, standards, etc. Returns each collection's slug, name, description, and field schema. Start here before create-entry so you know which collections exist and what fields they expect.",
|
|
197
|
+
annotations: { readOnlyHint: true }
|
|
198
|
+
},
|
|
199
|
+
async () => {
|
|
200
|
+
const collections = await mcpQuery("kb.listCollections");
|
|
201
|
+
if (collections.length === 0) {
|
|
202
|
+
return { content: [{ type: "text", text: "No collections found in this workspace." }] };
|
|
203
|
+
}
|
|
204
|
+
const formatted = collections.map((c) => {
|
|
205
|
+
const fieldList = c.fields.map((f) => ` - \`${f.key}\` (${f.type}${f.required ? ", required" : ""}${f.searchable ? ", searchable" : ""})`).join("\n");
|
|
206
|
+
return `## ${c.name} (\`${c.slug}\`)
|
|
207
|
+
${c.description || "_No description_"}
|
|
208
|
+
|
|
209
|
+
**Fields:**
|
|
210
|
+
${fieldList}`;
|
|
211
|
+
}).join("\n\n---\n\n");
|
|
212
|
+
return {
|
|
213
|
+
content: [{ type: "text", text: `# Knowledge Collections (${collections.length})
|
|
214
|
+
|
|
215
|
+
${formatted}` }]
|
|
216
|
+
};
|
|
217
|
+
}
|
|
218
|
+
);
|
|
219
|
+
server2.registerTool(
|
|
220
|
+
"list-entries",
|
|
221
|
+
{
|
|
222
|
+
title: "Browse Entries",
|
|
223
|
+
description: "List entries in a collection, with optional filters for status, tag, or label. Returns entry IDs, names, status, and a data preview. Use list-collections first to discover available collection slugs.",
|
|
224
|
+
inputSchema: {
|
|
225
|
+
collection: z.string().optional().describe("Collection slug, e.g. 'glossary', 'tracking-events', 'business-rules'"),
|
|
226
|
+
status: z.string().optional().describe("Filter: draft | active | verified | deprecated"),
|
|
227
|
+
tag: z.string().optional().describe("Filter by internal tag, e.g. 'health:ambiguous'"),
|
|
228
|
+
label: z.string().optional().describe("Filter by label slug \u2014 matches entries across all collections")
|
|
229
|
+
},
|
|
230
|
+
annotations: { readOnlyHint: true }
|
|
231
|
+
},
|
|
232
|
+
async ({ collection, status, tag, label }) => {
|
|
233
|
+
let entries;
|
|
234
|
+
if (label) {
|
|
235
|
+
entries = await mcpQuery("kb.listEntriesByLabel", { labelSlug: label });
|
|
236
|
+
if (status) entries = entries.filter((e) => e.status === status);
|
|
237
|
+
} else {
|
|
238
|
+
entries = await mcpQuery("kb.listEntries", {
|
|
239
|
+
collectionSlug: collection,
|
|
240
|
+
status,
|
|
241
|
+
tag
|
|
242
|
+
});
|
|
243
|
+
}
|
|
244
|
+
if (entries.length === 0) {
|
|
245
|
+
return { content: [{ type: "text", text: "No entries match the given filters." }] };
|
|
246
|
+
}
|
|
247
|
+
const formatted = entries.map((e) => {
|
|
248
|
+
const id = e.entryId ? `**${e.entryId}:** ` : "";
|
|
249
|
+
const dataPreview = e.data ? Object.entries(e.data).slice(0, 4).map(([k, v]) => ` ${k}: ${typeof v === "string" ? v.substring(0, 120) : JSON.stringify(v)}`).join("\n") : "";
|
|
250
|
+
return `- ${id}${e.name} \`${e.status}\`${dataPreview ? `
|
|
251
|
+
${dataPreview}` : ""}`;
|
|
252
|
+
}).join("\n\n");
|
|
253
|
+
const scope = collection ? ` in \`${collection}\`` : "";
|
|
254
|
+
return {
|
|
255
|
+
content: [{ type: "text", text: `# Entries${scope} (${entries.length})
|
|
256
|
+
|
|
257
|
+
${formatted}` }]
|
|
258
|
+
};
|
|
259
|
+
}
|
|
260
|
+
);
|
|
261
|
+
server2.registerTool(
|
|
262
|
+
"get-entry",
|
|
263
|
+
{
|
|
264
|
+
title: "Look Up Entry",
|
|
265
|
+
description: "Retrieve a single knowledge entry by its human-readable ID (e.g. 'T-SUPPLIER', 'BR-001', 'EVT-workspace_created'). Returns the full record: all data fields, labels, relations, and change history. Use kb-search or list-entries first to discover entry IDs.",
|
|
266
|
+
inputSchema: {
|
|
267
|
+
entryId: z.string().describe("Entry ID, e.g. 'T-SUPPLIER', 'BR-001', 'EVT-workspace_created'")
|
|
268
|
+
},
|
|
269
|
+
annotations: { readOnlyHint: true }
|
|
270
|
+
},
|
|
271
|
+
async ({ entryId }) => {
|
|
272
|
+
const entry = await mcpQuery("kb.getEntry", { entryId });
|
|
273
|
+
if (!entry) {
|
|
274
|
+
return { content: [{ type: "text", text: `Entry \`${entryId}\` not found. Try kb-search to find the right ID.` }] };
|
|
275
|
+
}
|
|
276
|
+
const lines = [
|
|
277
|
+
`# ${entry.entryId ? `${entry.entryId}: ` : ""}${entry.name}`,
|
|
278
|
+
"",
|
|
279
|
+
`**Status:** ${entry.status}`
|
|
280
|
+
];
|
|
281
|
+
if (entry.data && typeof entry.data === "object") {
|
|
282
|
+
lines.push("");
|
|
283
|
+
for (const [key, val] of Object.entries(entry.data)) {
|
|
284
|
+
const display = typeof val === "string" ? val : JSON.stringify(val);
|
|
285
|
+
lines.push(`**${key}:** ${display}`);
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
if (entry.tags?.length > 0) {
|
|
289
|
+
lines.push("", `**Tags:** ${entry.tags.join(", ")}`);
|
|
290
|
+
}
|
|
291
|
+
if (entry.labels?.length > 0) {
|
|
292
|
+
lines.push("", `**Labels:** ${entry.labels.map((l) => `\`${l.slug ?? l.name}\``).join(", ")}`);
|
|
293
|
+
}
|
|
294
|
+
if (entry.relations?.length > 0) {
|
|
295
|
+
lines.push("", "## Relations");
|
|
296
|
+
for (const r of entry.relations) {
|
|
297
|
+
const arrow = r.direction === "outgoing" ? "\u2192" : "\u2190";
|
|
298
|
+
const other = r.otherEntryId ? `${r.otherEntryId}: ${r.otherName}` : r.otherName ?? "unknown";
|
|
299
|
+
lines.push(`- ${arrow} **${r.type}** ${other}`);
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
if (entry.history?.length > 0) {
|
|
303
|
+
lines.push("", "## History (last 10)");
|
|
304
|
+
for (const h of entry.history.slice(-10)) {
|
|
305
|
+
const date = new Date(h.timestamp).toISOString().split("T")[0];
|
|
306
|
+
lines.push(`- ${date}: ${h.event}${h.changedBy ? ` _(${h.changedBy})_` : ""}`);
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
return { content: [{ type: "text", text: lines.join("\n") }] };
|
|
310
|
+
}
|
|
311
|
+
);
|
|
312
|
+
const governedCollections = /* @__PURE__ */ new Set([
|
|
313
|
+
"glossary",
|
|
314
|
+
"business-rules",
|
|
315
|
+
"principles",
|
|
316
|
+
"standards",
|
|
317
|
+
"strategy"
|
|
318
|
+
]);
|
|
319
|
+
server2.registerTool(
|
|
320
|
+
"create-entry",
|
|
321
|
+
{
|
|
322
|
+
title: "Create Entry",
|
|
323
|
+
description: "Create a new knowledge entry. Provide the collection slug, a display name, status, and data matching the collection's field schema. Call list-collections first to see available collections and their field definitions. Governed collections (glossary, business-rules, principles, standards, strategy) require status 'draft' \u2014 to promote to 'active' or 'verified', raise a tension or use update-entry after approval.",
|
|
324
|
+
inputSchema: {
|
|
325
|
+
collection: z.string().describe("Collection slug, e.g. 'tracking-events', 'standards', 'glossary'"),
|
|
326
|
+
entryId: z.string().optional().describe("Human-readable ID, e.g. 'EVT-workspace_created', 'STD-posthog-events'"),
|
|
327
|
+
name: z.string().describe("Display name"),
|
|
328
|
+
status: z.string().default("draft").describe("Lifecycle status: draft | active | verified | deprecated"),
|
|
329
|
+
data: z.record(z.unknown()).describe("Data object \u2014 keys must match the collection's field definitions"),
|
|
330
|
+
order: z.number().optional().describe("Manual sort order within the collection")
|
|
331
|
+
},
|
|
332
|
+
annotations: { destructiveHint: false }
|
|
333
|
+
},
|
|
334
|
+
async ({ collection, entryId, name, status, data, order }) => {
|
|
335
|
+
if (governedCollections.has(collection) && status !== "draft" && status !== "deprecated") {
|
|
336
|
+
return {
|
|
337
|
+
content: [{
|
|
338
|
+
type: "text",
|
|
339
|
+
text: `# Governance Required
|
|
340
|
+
|
|
341
|
+
The \`${collection}\` collection is governed. New entries must be created with status \`draft\`.
|
|
342
|
+
|
|
343
|
+
**How to proceed:**
|
|
344
|
+
1. Create the entry with status \`draft\` (treated as a proposal)
|
|
345
|
+
2. Raise a tension in the \`tensions\` collection to request promotion
|
|
346
|
+
3. After approval, use \`update-entry\` to change status to \`active\` or \`verified\``
|
|
347
|
+
}]
|
|
348
|
+
};
|
|
349
|
+
}
|
|
350
|
+
try {
|
|
351
|
+
const id = await mcpMutation("kb.createEntry", {
|
|
352
|
+
collectionSlug: collection,
|
|
353
|
+
entryId,
|
|
354
|
+
name,
|
|
355
|
+
status,
|
|
356
|
+
data,
|
|
357
|
+
order
|
|
358
|
+
});
|
|
359
|
+
return {
|
|
360
|
+
content: [{ type: "text", text: `# Entry Created
|
|
361
|
+
|
|
362
|
+
**${entryId ?? name}** added to \`${collection}\` as \`${status}\`.
|
|
363
|
+
|
|
364
|
+
Internal ID: ${id}` }]
|
|
365
|
+
};
|
|
366
|
+
} catch (error) {
|
|
367
|
+
const msg = error instanceof Error ? error.message : String(error);
|
|
368
|
+
if (msg.includes("Duplicate entry") || msg.includes("already exists")) {
|
|
369
|
+
return {
|
|
370
|
+
content: [{
|
|
371
|
+
type: "text",
|
|
372
|
+
text: `# Cannot Create \u2014 Duplicate Detected
|
|
373
|
+
|
|
374
|
+
${msg}
|
|
375
|
+
|
|
376
|
+
**What to do:**
|
|
377
|
+
- Use \`get-entry\` to inspect the existing entry
|
|
378
|
+
- Use \`update-entry\` to modify it
|
|
379
|
+
- If a genuinely new entry is needed, raise a tension to propose it`
|
|
380
|
+
}]
|
|
381
|
+
};
|
|
382
|
+
}
|
|
383
|
+
throw error;
|
|
384
|
+
}
|
|
385
|
+
}
|
|
386
|
+
);
|
|
387
|
+
server2.registerTool(
|
|
388
|
+
"update-entry",
|
|
389
|
+
{
|
|
390
|
+
title: "Update Entry",
|
|
391
|
+
description: "Update an existing entry by its human-readable ID. Only provide the fields you want to change \u2014 data fields are merged with existing values. Use get-entry first to see current values. SOS-020: Cannot update tension status via MCP \u2014 process decides (use SynergyOS UI after approval).",
|
|
392
|
+
inputSchema: {
|
|
393
|
+
entryId: z.string().describe("Entry ID to update, e.g. 'T-SUPPLIER', 'BR-001'"),
|
|
394
|
+
name: z.string().optional().describe("New display name"),
|
|
395
|
+
status: z.string().optional().describe("New status: draft | active | verified | deprecated"),
|
|
396
|
+
data: z.record(z.unknown()).optional().describe("Fields to update (merged with existing data)"),
|
|
397
|
+
order: z.number().optional().describe("New sort order")
|
|
398
|
+
},
|
|
399
|
+
annotations: { idempotentHint: true, destructiveHint: false }
|
|
400
|
+
},
|
|
401
|
+
async ({ entryId, name, status, data, order }) => {
|
|
402
|
+
try {
|
|
403
|
+
const id = await mcpMutation("kb.updateEntry", {
|
|
404
|
+
entryId,
|
|
405
|
+
name,
|
|
406
|
+
status,
|
|
407
|
+
data,
|
|
408
|
+
order
|
|
409
|
+
});
|
|
410
|
+
return {
|
|
411
|
+
content: [{ type: "text", text: `# Entry Updated
|
|
412
|
+
|
|
413
|
+
**${entryId}** has been updated.
|
|
414
|
+
|
|
415
|
+
Internal ID: ${id}` }]
|
|
416
|
+
};
|
|
417
|
+
} catch (error) {
|
|
418
|
+
const msg = error instanceof Error ? error.message : String(error);
|
|
419
|
+
if (msg.includes("SOS-020")) {
|
|
420
|
+
return {
|
|
421
|
+
content: [{
|
|
422
|
+
type: "text",
|
|
423
|
+
text: `# SOS-020: Tension Status Cannot Be Changed via MCP
|
|
424
|
+
|
|
425
|
+
Tension status (open, in-progress, closed) must be changed through the defined process, not via MCP.
|
|
426
|
+
|
|
427
|
+
**What you can do:**
|
|
428
|
+
- Create tensions: \`create-entry collection=tensions name="..." status=open\`
|
|
429
|
+
- List tensions: \`list-entries collection=tensions\`
|
|
430
|
+
- Update non-status fields (raised, date, priority, description) via \`update-entry\`
|
|
431
|
+
- After process approval, a human uses the SynergyOS UI to change status
|
|
432
|
+
|
|
433
|
+
Process criteria (TBD): e.g. 3+ users approved, or 7 days without valid concerns.`
|
|
434
|
+
}]
|
|
435
|
+
};
|
|
436
|
+
}
|
|
437
|
+
throw error;
|
|
438
|
+
}
|
|
439
|
+
}
|
|
440
|
+
);
|
|
441
|
+
server2.registerTool(
|
|
442
|
+
"kb-search",
|
|
443
|
+
{
|
|
444
|
+
title: "Search Knowledge Base",
|
|
445
|
+
description: "Full-text search across all knowledge entries. Returns entry names, collection, status, and a description preview. Scope results to a specific collection (e.g. collection='business-rules') or filter by status (e.g. status='active'). Use this to discover entries before calling get-entry for full details.",
|
|
446
|
+
inputSchema: {
|
|
447
|
+
query: z.string().describe("Search text (min 2 characters)"),
|
|
448
|
+
collection: z.string().optional().describe("Scope to a collection slug, e.g. 'business-rules', 'glossary', 'tracking-events'"),
|
|
449
|
+
status: z.string().optional().describe("Filter by status: draft | active | verified | deprecated")
|
|
450
|
+
},
|
|
451
|
+
annotations: { readOnlyHint: true, openWorldHint: true }
|
|
452
|
+
},
|
|
453
|
+
async ({ query, collection, status }) => {
|
|
454
|
+
const scope = collection ? ` in \`${collection}\`` : "";
|
|
455
|
+
await server2.sendLoggingMessage({ level: "info", data: `Searching${scope} for "${query}"...`, logger: "product-os" });
|
|
456
|
+
const [results, collections] = await Promise.all([
|
|
457
|
+
mcpQuery("kb.searchEntries", { query, collectionSlug: collection, status }),
|
|
458
|
+
mcpQuery("kb.listCollections")
|
|
459
|
+
]);
|
|
460
|
+
if (results.length === 0) {
|
|
461
|
+
return { content: [{ type: "text", text: `No results for "${query}"${scope}. Try a broader search or check list-collections for available data.` }] };
|
|
462
|
+
}
|
|
463
|
+
const collMap = /* @__PURE__ */ new Map();
|
|
464
|
+
for (const c of collections) {
|
|
465
|
+
collMap.set(c._id, { name: c.name, slug: c.slug });
|
|
466
|
+
}
|
|
467
|
+
const countsBySlug = /* @__PURE__ */ new Map();
|
|
468
|
+
for (const e of results) {
|
|
469
|
+
const col = collMap.get(e.collectionId);
|
|
470
|
+
const slug = col?.slug ?? "unknown";
|
|
471
|
+
countsBySlug.set(slug, (countsBySlug.get(slug) ?? 0) + 1);
|
|
472
|
+
}
|
|
473
|
+
const collSummary = [...countsBySlug.entries()].sort((a, b) => b[1] - a[1]).map(([slug, count]) => `${count} ${slug}`).join(", ");
|
|
474
|
+
const formatted = results.map((e) => {
|
|
475
|
+
const id = e.entryId ? `**${e.entryId}:** ` : "";
|
|
476
|
+
const col = collMap.get(e.collectionId);
|
|
477
|
+
const colTag = col ? ` [${col.slug}]` : "";
|
|
478
|
+
const desc = extractPreview(e.data, 150);
|
|
479
|
+
const preview = desc ? `
|
|
480
|
+
${desc}` : "";
|
|
481
|
+
return `- ${id}${e.name} \`${e.status}\`${colTag}${preview}`;
|
|
482
|
+
}).join("\n");
|
|
483
|
+
const header = `# Search Results for "${query}"${scope} (${results.length} match${results.length === 1 ? "" : "es"})
|
|
484
|
+
|
|
485
|
+
**By collection:** ${collSummary}`;
|
|
486
|
+
const footer = `_Tip: Use \`collection\` param to scope search. Use get-entry with an entry ID for full details._`;
|
|
487
|
+
return {
|
|
488
|
+
content: [{ type: "text", text: `${header}
|
|
489
|
+
|
|
490
|
+
${formatted}
|
|
491
|
+
|
|
492
|
+
${footer}` }]
|
|
493
|
+
};
|
|
494
|
+
}
|
|
495
|
+
);
|
|
496
|
+
server2.registerTool(
|
|
497
|
+
"get-history",
|
|
498
|
+
{
|
|
499
|
+
title: "Entry Change History",
|
|
500
|
+
description: "Get the audit trail for an entry \u2014 when it was created, updated, status-changed, etc. Returns timestamped events with change details.",
|
|
501
|
+
inputSchema: {
|
|
502
|
+
entryId: z.string().describe("Entry ID, e.g. 'T-SUPPLIER', 'BR-001'")
|
|
503
|
+
},
|
|
504
|
+
annotations: { readOnlyHint: true }
|
|
505
|
+
},
|
|
506
|
+
async ({ entryId }) => {
|
|
507
|
+
const history = await mcpQuery("kb.listEntryHistory", { entryId });
|
|
508
|
+
if (history.length === 0) {
|
|
509
|
+
return { content: [{ type: "text", text: `No history found for \`${entryId}\`.` }] };
|
|
510
|
+
}
|
|
511
|
+
const formatted = history.map((h) => {
|
|
512
|
+
const date = new Date(h.timestamp).toISOString();
|
|
513
|
+
const changes = h.changes ? ` \u2014 ${JSON.stringify(h.changes)}` : "";
|
|
514
|
+
return `- **${date}** ${h.event}${h.changedBy ? ` _(${h.changedBy})_` : ""}${changes}`;
|
|
515
|
+
}).join("\n");
|
|
516
|
+
return {
|
|
517
|
+
content: [{ type: "text", text: `# History for \`${entryId}\` (${history.length} events)
|
|
518
|
+
|
|
519
|
+
${formatted}` }]
|
|
520
|
+
};
|
|
521
|
+
}
|
|
522
|
+
);
|
|
523
|
+
server2.registerTool(
|
|
524
|
+
"relate-entries",
|
|
525
|
+
{
|
|
526
|
+
title: "Link Two Entries",
|
|
527
|
+
description: "Create a typed relation between two entries, building the knowledge graph. Use get-entry to see existing relations before adding new ones.\n\nRecommended relation types (extensible \u2014 any string is accepted):\n- related_to, depends_on, replaces, conflicts_with, references, confused_with\n- governs \u2014 a rule constrains behavior of a feature\n- defines_term_for \u2014 a glossary term is canonical vocabulary for a feature/area\n- belongs_to \u2014 a feature belongs to a product area or parent concept\n- informs \u2014 a decision or insight informs a feature\n- surfaces_tension_in \u2014 a tension exists within a feature area\n\nCheck glossary for relation type definitions if unsure which to use.",
|
|
528
|
+
inputSchema: {
|
|
529
|
+
from: z.string().describe("Source entry ID, e.g. 'T-SUPPLIER'"),
|
|
530
|
+
to: z.string().describe("Target entry ID, e.g. 'BR-001'"),
|
|
531
|
+
type: z.string().describe("Relation type \u2014 use a recommended type or any descriptive string")
|
|
532
|
+
},
|
|
533
|
+
annotations: { destructiveHint: false }
|
|
534
|
+
},
|
|
535
|
+
async ({ from, to, type }) => {
|
|
536
|
+
await mcpMutation("kb.createEntryRelation", {
|
|
537
|
+
fromEntryId: from,
|
|
538
|
+
toEntryId: to,
|
|
539
|
+
type
|
|
540
|
+
});
|
|
541
|
+
return {
|
|
542
|
+
content: [{ type: "text", text: `# Relation Created
|
|
543
|
+
|
|
544
|
+
**${from}** \u2014[${type}]\u2192 **${to}**` }]
|
|
545
|
+
};
|
|
546
|
+
}
|
|
547
|
+
);
|
|
548
|
+
server2.registerTool(
|
|
549
|
+
"find-related",
|
|
550
|
+
{
|
|
551
|
+
title: "Find Related Entries",
|
|
552
|
+
description: "Navigate the knowledge graph \u2014 find all entries related to a given entry. Shows incoming references (what points to this entry), outgoing references (what this entry points to), or both. Use after get-entry to explore connections, or to answer 'what depends on X?' or 'what references Y?'",
|
|
553
|
+
inputSchema: {
|
|
554
|
+
entryId: z.string().describe("Entry ID, e.g. 'GT-019', 'SOS-006'"),
|
|
555
|
+
direction: z.enum(["incoming", "outgoing", "both"]).default("both").describe("Filter: 'incoming' = what references this entry, 'outgoing' = what this entry references")
|
|
556
|
+
},
|
|
557
|
+
annotations: { readOnlyHint: true }
|
|
558
|
+
},
|
|
559
|
+
async ({ entryId, direction }) => {
|
|
560
|
+
const relations = await mcpQuery("kb.listEntryRelations", { entryId });
|
|
561
|
+
if (relations.length === 0) {
|
|
562
|
+
return { content: [{ type: "text", text: `No relations found for \`${entryId}\`. Use relate-entries to create connections.` }] };
|
|
563
|
+
}
|
|
564
|
+
const sourceEntry = await mcpQuery("kb.getEntry", { entryId });
|
|
565
|
+
if (!sourceEntry) {
|
|
566
|
+
return { content: [{ type: "text", text: `Entry \`${entryId}\` not found. Try kb-search to find the right ID.` }] };
|
|
567
|
+
}
|
|
568
|
+
const sourceInternalId = sourceEntry._id;
|
|
569
|
+
const MAX_RELATIONS = 25;
|
|
570
|
+
const truncated = relations.length > MAX_RELATIONS;
|
|
571
|
+
const capped = relations.slice(0, MAX_RELATIONS);
|
|
572
|
+
const otherIds = /* @__PURE__ */ new Set();
|
|
573
|
+
for (const r of capped) {
|
|
574
|
+
const otherId = r.fromId === sourceInternalId ? r.toId : r.fromId;
|
|
575
|
+
otherIds.add(otherId);
|
|
576
|
+
}
|
|
577
|
+
const otherEntries = /* @__PURE__ */ new Map();
|
|
578
|
+
for (const id of otherIds) {
|
|
579
|
+
const entry = await mcpQuery("kb.getEntry", { id });
|
|
580
|
+
if (entry) {
|
|
581
|
+
otherEntries.set(entry._id, { entryId: entry.entryId, name: entry.name, collectionId: entry.collectionId });
|
|
582
|
+
}
|
|
583
|
+
}
|
|
584
|
+
const collections = await mcpQuery("kb.listCollections");
|
|
585
|
+
const collMap = /* @__PURE__ */ new Map();
|
|
586
|
+
for (const c of collections) collMap.set(c._id, c.slug);
|
|
587
|
+
const lines = [`# Relations for ${entryId}: ${sourceEntry.name}`, ""];
|
|
588
|
+
const enriched = capped.map((r) => {
|
|
589
|
+
const isOutgoing = r.fromId === sourceInternalId;
|
|
590
|
+
const otherId = isOutgoing ? r.toId : r.fromId;
|
|
591
|
+
const other = otherEntries.get(otherId);
|
|
592
|
+
const otherLabel = other?.entryId ? `${other.entryId}: ${other.name}` : other?.name ?? "(deleted)";
|
|
593
|
+
const colSlug = other ? collMap.get(other.collectionId) ?? "unknown" : "unknown";
|
|
594
|
+
return { isOutgoing, type: r.type, otherLabel, colSlug };
|
|
595
|
+
});
|
|
596
|
+
const outgoing = enriched.filter((r) => r.isOutgoing);
|
|
597
|
+
const incoming = enriched.filter((r) => !r.isOutgoing);
|
|
598
|
+
if ((direction === "outgoing" || direction === "both") && outgoing.length > 0) {
|
|
599
|
+
lines.push(`## Outgoing (${outgoing.length})`);
|
|
600
|
+
for (const r of outgoing) {
|
|
601
|
+
lines.push(`- \u2192 **${r.type}** ${r.otherLabel} [${r.colSlug}]`);
|
|
602
|
+
}
|
|
603
|
+
lines.push("");
|
|
604
|
+
}
|
|
605
|
+
if ((direction === "incoming" || direction === "both") && incoming.length > 0) {
|
|
606
|
+
lines.push(`## Incoming (${incoming.length})`);
|
|
607
|
+
for (const r of incoming) {
|
|
608
|
+
lines.push(`- \u2190 **${r.type}** ${r.otherLabel} [${r.colSlug}]`);
|
|
609
|
+
}
|
|
610
|
+
lines.push("");
|
|
611
|
+
}
|
|
612
|
+
const shown = direction === "outgoing" ? outgoing : direction === "incoming" ? incoming : enriched;
|
|
613
|
+
if (shown.length === 0) {
|
|
614
|
+
lines.push(`No ${direction} relations found for \`${entryId}\`.`);
|
|
615
|
+
}
|
|
616
|
+
if (truncated) {
|
|
617
|
+
lines.push(`_Showing first ${MAX_RELATIONS} of ${relations.length} relations. Use get-entry for the full picture._`);
|
|
618
|
+
}
|
|
619
|
+
return { content: [{ type: "text", text: lines.join("\n") }] };
|
|
620
|
+
}
|
|
621
|
+
);
|
|
622
|
+
server2.registerTool(
|
|
623
|
+
"gather-context",
|
|
624
|
+
{
|
|
625
|
+
title: "Gather Full Context",
|
|
626
|
+
description: "Assemble the full knowledge context around an entry by traversing the knowledge graph. Returns all related entries grouped by collection \u2014 glossary terms, business rules, tensions, decisions, features, etc. Use this when starting work on a feature or investigating an area to get the complete picture in one call.\n\nExample: gather-context entryId='FEAT-001' returns all glossary terms, business rules, and tensions linked to that feature.",
|
|
627
|
+
inputSchema: {
|
|
628
|
+
entryId: z.string().describe("Entry ID, e.g. 'FEAT-001', 'GT-019', 'BR-007'"),
|
|
629
|
+
maxHops: z.number().min(1).max(3).default(2).describe("How many relation hops to traverse (1=direct only, 2=default, 3=wide net)")
|
|
630
|
+
},
|
|
631
|
+
annotations: { readOnlyHint: true }
|
|
632
|
+
},
|
|
633
|
+
async ({ entryId, maxHops }) => {
|
|
634
|
+
const result = await mcpQuery("kb.gatherContext", { entryId, maxHops });
|
|
635
|
+
if (!result?.root) {
|
|
636
|
+
return { content: [{ type: "text", text: `Entry \`${entryId}\` not found. Try kb-search to find the right ID.` }] };
|
|
637
|
+
}
|
|
638
|
+
if (result.related.length === 0) {
|
|
639
|
+
return {
|
|
640
|
+
content: [{
|
|
641
|
+
type: "text",
|
|
642
|
+
text: `# Context for ${result.root.entryId}: ${result.root.name}
|
|
643
|
+
|
|
644
|
+
_No relations found._ This entry is not yet connected to the knowledge graph.
|
|
645
|
+
|
|
646
|
+
Use \`suggest-links\` to discover potential connections, or \`relate-entries\` to link manually.`
|
|
647
|
+
}]
|
|
648
|
+
};
|
|
649
|
+
}
|
|
650
|
+
const byCollection = /* @__PURE__ */ new Map();
|
|
651
|
+
for (const entry of result.related) {
|
|
652
|
+
const key = entry.collectionName;
|
|
653
|
+
if (!byCollection.has(key)) byCollection.set(key, []);
|
|
654
|
+
byCollection.get(key).push(entry);
|
|
655
|
+
}
|
|
656
|
+
const lines = [
|
|
657
|
+
`# Context for ${result.root.entryId}: ${result.root.name}`,
|
|
658
|
+
`_${result.totalRelations} related entries across ${byCollection.size} collections (${result.hopsTraversed} hops traversed)_`,
|
|
659
|
+
""
|
|
660
|
+
];
|
|
661
|
+
for (const [collName, entries] of byCollection) {
|
|
662
|
+
lines.push(`## ${collName} (${entries.length})`);
|
|
663
|
+
for (const e of entries) {
|
|
664
|
+
const arrow = e.relationDirection === "outgoing" ? "\u2192" : "\u2190";
|
|
665
|
+
const hopLabel = e.hop > 1 ? ` (hop ${e.hop})` : "";
|
|
666
|
+
const id = e.entryId ? `${e.entryId}: ` : "";
|
|
667
|
+
lines.push(`- ${arrow} **${e.relationType}** ${id}${e.name}${hopLabel}`);
|
|
668
|
+
}
|
|
669
|
+
lines.push("");
|
|
670
|
+
}
|
|
671
|
+
return { content: [{ type: "text", text: lines.join("\n") }] };
|
|
672
|
+
}
|
|
673
|
+
);
|
|
674
|
+
server2.registerTool(
|
|
675
|
+
"suggest-links",
|
|
676
|
+
{
|
|
677
|
+
title: "Suggest Links",
|
|
678
|
+
description: "Discover potential connections for an entry by scanning the knowledge base for related content. Returns ranked suggestions based on text similarity \u2014 review them and use relate-entries to create the ones that make sense.\n\nThis is a discovery tool, not auto-linking. Always review suggestions before linking.",
|
|
679
|
+
inputSchema: {
|
|
680
|
+
entryId: z.string().describe("Entry ID to find suggestions for, e.g. 'FEAT-001'"),
|
|
681
|
+
limit: z.number().min(1).max(20).default(10).describe("Max number of suggestions to return")
|
|
682
|
+
},
|
|
683
|
+
annotations: { readOnlyHint: true }
|
|
684
|
+
},
|
|
685
|
+
async ({ entryId, limit }) => {
|
|
686
|
+
const entry = await mcpQuery("kb.getEntry", { entryId });
|
|
687
|
+
if (!entry) {
|
|
688
|
+
return { content: [{ type: "text", text: `Entry \`${entryId}\` not found. Try kb-search to find the right ID.` }] };
|
|
689
|
+
}
|
|
690
|
+
const searchTerms = [entry.name];
|
|
691
|
+
if (entry.data?.description) searchTerms.push(entry.data.description);
|
|
692
|
+
if (entry.data?.canonical) searchTerms.push(entry.data.canonical);
|
|
693
|
+
if (entry.data?.rationale) searchTerms.push(entry.data.rationale);
|
|
694
|
+
if (entry.data?.rule) searchTerms.push(entry.data.rule);
|
|
695
|
+
const queryText = searchTerms.join(" ").replace(/[^\w\s]/g, " ").split(/\s+/).filter((w) => w.length > 3).slice(0, 8).join(" ");
|
|
696
|
+
if (!queryText) {
|
|
697
|
+
return { content: [{ type: "text", text: `Entry \`${entryId}\` has too little text content to generate suggestions.` }] };
|
|
698
|
+
}
|
|
699
|
+
const results = await mcpQuery("kb.searchEntries", { query: queryText });
|
|
700
|
+
if (!results || results.length === 0) {
|
|
701
|
+
return { content: [{ type: "text", text: `No suggestions found for \`${entryId}\`. The knowledge base may need more entries.` }] };
|
|
702
|
+
}
|
|
703
|
+
const existingRelations = await mcpQuery("kb.listEntryRelations", { entryId });
|
|
704
|
+
const relatedIds = new Set(
|
|
705
|
+
existingRelations.flatMap((r) => [r.fromId, r.toId])
|
|
706
|
+
);
|
|
707
|
+
const collections = await mcpQuery("kb.listCollections");
|
|
708
|
+
const collMap = /* @__PURE__ */ new Map();
|
|
709
|
+
for (const c of collections) collMap.set(c._id, c.slug);
|
|
710
|
+
const suggestions = results.filter((r) => r._id !== entry._id && !relatedIds.has(r._id)).slice(0, limit).map((r) => ({
|
|
711
|
+
entryId: r.entryId,
|
|
712
|
+
name: r.name,
|
|
713
|
+
collection: collMap.get(r.collectionId) ?? "unknown",
|
|
714
|
+
preview: extractPreview(r.data, 80)
|
|
715
|
+
}));
|
|
716
|
+
if (suggestions.length === 0) {
|
|
717
|
+
return { content: [{ type: "text", text: `No new link suggestions for \`${entryId}\` \u2014 it may already be well-connected, or no similar entries exist.` }] };
|
|
718
|
+
}
|
|
719
|
+
const lines = [
|
|
720
|
+
`# Link Suggestions for ${entryId}: ${entry.name}`,
|
|
721
|
+
`_${suggestions.length} potential connections found. Review and use \`relate-entries\` to create the ones that make sense._`,
|
|
722
|
+
""
|
|
723
|
+
];
|
|
724
|
+
for (let i = 0; i < suggestions.length; i++) {
|
|
725
|
+
const s = suggestions[i];
|
|
726
|
+
const preview = s.preview ? ` \u2014 ${s.preview}` : "";
|
|
727
|
+
lines.push(`${i + 1}. **${s.entryId ?? "(no ID)"}**: ${s.name} [${s.collection}]${preview}`);
|
|
728
|
+
}
|
|
729
|
+
lines.push("");
|
|
730
|
+
lines.push("**To link:** `relate-entries from='FEAT-001' to='GT-019' type='defines_term_for'`");
|
|
731
|
+
lines.push("");
|
|
732
|
+
lines.push("_Recommended relation types: governs, defines_term_for, belongs_to, informs, surfaces_tension_in, related_to, depends_on_");
|
|
733
|
+
return { content: [{ type: "text", text: lines.join("\n") }] };
|
|
734
|
+
}
|
|
735
|
+
);
|
|
736
|
+
server2.registerTool(
|
|
737
|
+
"quick-capture",
|
|
738
|
+
{
|
|
739
|
+
title: "Quick Capture",
|
|
740
|
+
description: "Quickly capture a knowledge entry with just a name and description \u2014 no need to look up the full field schema first. Always creates as 'draft' status with sensible defaults for remaining fields. Use update-entry later to fill in details. Embodies 'Capture Now, Curate Later' (PRI-81cbdq).",
|
|
741
|
+
inputSchema: {
|
|
742
|
+
collection: z.string().describe("Collection slug, e.g. 'business-rules', 'glossary', 'tensions', 'decisions'"),
|
|
743
|
+
name: z.string().describe("Display name for the entry"),
|
|
744
|
+
description: z.string().describe("Short description \u2014 the essential context to capture now"),
|
|
745
|
+
entryId: z.string().optional().describe("Optional human-readable ID (e.g. 'SOS-020', 'GT-031')")
|
|
746
|
+
},
|
|
747
|
+
annotations: { destructiveHint: false }
|
|
748
|
+
},
|
|
749
|
+
async ({ collection, name, description, entryId }) => {
|
|
750
|
+
const col = await mcpQuery("kb.getCollection", { slug: collection });
|
|
751
|
+
if (!col) {
|
|
752
|
+
return { content: [{ type: "text", text: `Collection \`${collection}\` not found. Use list-collections to see available collections.` }] };
|
|
753
|
+
}
|
|
754
|
+
const data = {};
|
|
755
|
+
const emptyFields = [];
|
|
756
|
+
for (const field of col.fields ?? []) {
|
|
757
|
+
const key = field.key;
|
|
758
|
+
if (key === "description" || key === "canonical" || key === "detail") {
|
|
759
|
+
data[key] = description;
|
|
760
|
+
} else if (field.type === "array" || field.type === "multi-select") {
|
|
761
|
+
data[key] = [];
|
|
762
|
+
emptyFields.push(key);
|
|
763
|
+
} else if (field.type === "select") {
|
|
764
|
+
data[key] = field.options?.[0] ?? "";
|
|
765
|
+
emptyFields.push(key);
|
|
766
|
+
} else {
|
|
767
|
+
data[key] = "";
|
|
768
|
+
emptyFields.push(key);
|
|
769
|
+
}
|
|
770
|
+
}
|
|
771
|
+
if (!data.description && !data.canonical && !data.detail) {
|
|
772
|
+
data.description = description;
|
|
773
|
+
}
|
|
774
|
+
try {
|
|
775
|
+
const id = await mcpMutation("kb.createEntry", {
|
|
776
|
+
collectionSlug: collection,
|
|
777
|
+
entryId,
|
|
778
|
+
name,
|
|
779
|
+
status: "draft",
|
|
780
|
+
data
|
|
781
|
+
});
|
|
782
|
+
const emptyNote = emptyFields.length > 0 ? `
|
|
783
|
+
|
|
784
|
+
**Fields to fill later** (via \`update-entry\`):
|
|
785
|
+
${emptyFields.map((f) => `- \`${f}\``).join("\n")}` : "";
|
|
786
|
+
return {
|
|
787
|
+
content: [{
|
|
788
|
+
type: "text",
|
|
789
|
+
text: `# Quick Capture \u2014 Done
|
|
790
|
+
|
|
791
|
+
**${entryId ?? name}** added to \`${collection}\` as \`draft\`.
|
|
792
|
+
|
|
793
|
+
Internal ID: ${id}${emptyNote}
|
|
794
|
+
|
|
795
|
+
_Use \`update-entry\` to fill in details when ready. Use \`get-entry\` to review._`
|
|
796
|
+
}]
|
|
797
|
+
};
|
|
798
|
+
} catch (error) {
|
|
799
|
+
const msg = error instanceof Error ? error.message : String(error);
|
|
800
|
+
if (msg.includes("Duplicate") || msg.includes("already exists")) {
|
|
801
|
+
return {
|
|
802
|
+
content: [{
|
|
803
|
+
type: "text",
|
|
804
|
+
text: `# Cannot Capture \u2014 Duplicate Detected
|
|
805
|
+
|
|
806
|
+
${msg}
|
|
807
|
+
|
|
808
|
+
Use \`get-entry\` to inspect the existing entry, or \`update-entry\` to modify it.`
|
|
809
|
+
}]
|
|
810
|
+
};
|
|
811
|
+
}
|
|
812
|
+
throw error;
|
|
813
|
+
}
|
|
814
|
+
}
|
|
815
|
+
);
|
|
816
|
+
server2.registerTool(
|
|
817
|
+
"load-context-for-task",
|
|
818
|
+
{
|
|
819
|
+
title: "Load Context for Task",
|
|
820
|
+
description: "Auto-load relevant domain knowledge for a task in a single call. Pass a natural-language task description; the tool searches the KB, traverses the knowledge graph, and returns a ranked set of entries (business rules, glossary terms, decisions, features, etc.) grouped by collection with a confidence score.\n\nUse this at the start of a conversation to ground the agent in domain context before writing code or making recommendations.\n\nConfidence levels:\n- high: 3+ direct KB matches \u2014 strong domain coverage\n- medium: 1-2 direct matches \u2014 partial coverage, may want to drill deeper\n- low: no direct matches but related entries found via graph traversal\n- none: no relevant entries found \u2014 KB may not cover this area yet",
|
|
821
|
+
inputSchema: {
|
|
822
|
+
taskDescription: z.string().describe("Natural-language description of the task or user message"),
|
|
823
|
+
maxResults: z.number().min(1).max(25).default(10).optional().describe("Max entries to return (default 10)"),
|
|
824
|
+
maxHops: z.number().min(1).max(3).default(2).optional().describe("Graph traversal depth from each search hit (default 2)")
|
|
825
|
+
},
|
|
826
|
+
annotations: { readOnlyHint: true, openWorldHint: true }
|
|
827
|
+
},
|
|
828
|
+
async ({ taskDescription, maxResults, maxHops }) => {
|
|
829
|
+
await server2.sendLoggingMessage({
|
|
830
|
+
level: "info",
|
|
831
|
+
data: `Loading context for task: "${taskDescription.substring(0, 80)}..."`,
|
|
832
|
+
logger: "product-os"
|
|
833
|
+
});
|
|
834
|
+
const result = await mcpQuery("kb.loadContextForTask", {
|
|
835
|
+
taskDescription,
|
|
836
|
+
maxResults: maxResults ?? 10,
|
|
837
|
+
maxHops: maxHops ?? 2
|
|
838
|
+
});
|
|
839
|
+
if (result.confidence === "none" || result.entries.length === 0) {
|
|
840
|
+
return {
|
|
841
|
+
content: [{
|
|
842
|
+
type: "text",
|
|
843
|
+
text: `# Context Loaded
|
|
844
|
+
|
|
845
|
+
**Confidence:** None
|
|
846
|
+
|
|
847
|
+
No KB context found for this task. The knowledge base may not cover this area yet.
|
|
848
|
+
|
|
849
|
+
_Consider capturing domain knowledge discovered during this task via \`smart-capture\`._`
|
|
850
|
+
}]
|
|
851
|
+
};
|
|
852
|
+
}
|
|
853
|
+
const byCollection = /* @__PURE__ */ new Map();
|
|
854
|
+
for (const entry of result.entries) {
|
|
855
|
+
const key = entry.collectionName;
|
|
856
|
+
if (!byCollection.has(key)) byCollection.set(key, []);
|
|
857
|
+
byCollection.get(key).push(entry);
|
|
858
|
+
}
|
|
859
|
+
const lines = [
|
|
860
|
+
`# Context Loaded`,
|
|
861
|
+
`**Confidence:** ${result.confidence.charAt(0).toUpperCase() + result.confidence.slice(1)}`,
|
|
862
|
+
`**Matched:** ${result.entries.length} entries across ${byCollection.size} collection${byCollection.size === 1 ? "" : "s"}`,
|
|
863
|
+
""
|
|
864
|
+
];
|
|
865
|
+
for (const [collName, entries] of byCollection) {
|
|
866
|
+
lines.push(`### ${collName} (${entries.length})`);
|
|
867
|
+
for (const e of entries) {
|
|
868
|
+
const id = e.entryId ? `**${e.entryId}:** ` : "";
|
|
869
|
+
const hopLabel = e.hop > 0 ? ` _(hop ${e.hop}${e.relationType ? `, ${e.relationType}` : ""})_` : "";
|
|
870
|
+
const preview = e.descriptionPreview ? `
|
|
871
|
+
${e.descriptionPreview}` : "";
|
|
872
|
+
const codePaths = e.codePaths.length > 0 ? `
|
|
873
|
+
Code: ${e.codePaths.join(", ")}` : "";
|
|
874
|
+
lines.push(`- ${id}${e.name}${hopLabel}${preview}${codePaths}`);
|
|
875
|
+
}
|
|
876
|
+
lines.push("");
|
|
877
|
+
}
|
|
878
|
+
lines.push(`_Use \`get-entry\` for full details on any entry._`);
|
|
879
|
+
return {
|
|
880
|
+
content: [{ type: "text", text: lines.join("\n") }]
|
|
881
|
+
};
|
|
882
|
+
}
|
|
883
|
+
);
|
|
884
|
+
server2.registerTool(
|
|
885
|
+
"review-rules",
|
|
886
|
+
{
|
|
887
|
+
title: "Review Business Rules",
|
|
888
|
+
description: "Surface all active business rules for a domain, formatted for compliance review. Use when reviewing code, designs, or decisions against ProductBrain governance. Optionally provide context (what you're building or reviewing) to help focus the review. This is the tool form of the review-against-rules prompt.",
|
|
889
|
+
inputSchema: {
|
|
890
|
+
domain: z.string().describe("Business rule domain, e.g. 'AI & MCP Integration', 'Governance & Decision-Making'"),
|
|
891
|
+
context: z.string().optional().describe("What you're reviewing \u2014 code change, design decision, file path, etc.")
|
|
892
|
+
},
|
|
893
|
+
annotations: { readOnlyHint: true }
|
|
894
|
+
},
|
|
895
|
+
async ({ domain, context }) => {
|
|
896
|
+
const entries = await mcpQuery("kb.listEntries", { collectionSlug: "business-rules" });
|
|
897
|
+
const domainLower = domain.toLowerCase();
|
|
898
|
+
const rules = entries.filter((e) => {
|
|
899
|
+
const ruleDomain = e.data?.domain ?? "";
|
|
900
|
+
return ruleDomain.toLowerCase() === domainLower || ruleDomain.toLowerCase().includes(domainLower);
|
|
901
|
+
});
|
|
902
|
+
if (rules.length === 0) {
|
|
903
|
+
const allDomains = [...new Set(entries.map((e) => e.data?.domain).filter(Boolean))];
|
|
904
|
+
return {
|
|
905
|
+
content: [{
|
|
906
|
+
type: "text",
|
|
907
|
+
text: `# No Rules Found for "${domain}"
|
|
908
|
+
|
|
909
|
+
Available domains:
|
|
910
|
+
${allDomains.map((d) => `- ${d}`).join("\n")}
|
|
911
|
+
|
|
912
|
+
_Try one of the domains above, or use kb-search to find rules by keyword._`
|
|
913
|
+
}]
|
|
914
|
+
};
|
|
915
|
+
}
|
|
916
|
+
const header = context ? `# Business Rules: ${domain}
|
|
917
|
+
|
|
918
|
+
**Review context:** ${context}
|
|
919
|
+
|
|
920
|
+
For each rule, assess: compliant, at risk, violation, or not applicable.
|
|
921
|
+
` : `# Business Rules: ${domain}
|
|
922
|
+
`;
|
|
923
|
+
const formatted = rules.map((r) => {
|
|
924
|
+
const id = r.entryId ? `**${r.entryId}:** ` : "";
|
|
925
|
+
const severity = r.data?.severity ? ` | Severity: ${r.data.severity}` : "";
|
|
926
|
+
const desc = r.data?.description ?? "";
|
|
927
|
+
const impact = r.data?.dataImpact ? `
|
|
928
|
+
Data impact: ${r.data.dataImpact}` : "";
|
|
929
|
+
const related = (r.data?.relatedRules ?? []).length > 0 ? `
|
|
930
|
+
Related: ${r.data.relatedRules.join(", ")}` : "";
|
|
931
|
+
return `### ${id}${r.name} \`${r.status}\`${severity}
|
|
932
|
+
|
|
933
|
+
${desc}${impact}${related}`;
|
|
934
|
+
}).join("\n\n---\n\n");
|
|
935
|
+
const footer = `
|
|
936
|
+
_${rules.length} rule${rules.length === 1 ? "" : "s"} in this domain. Use \`get-entry\` for full details. Use the \`draft-rule-from-context\` prompt to propose new rules._`;
|
|
937
|
+
return {
|
|
938
|
+
content: [{ type: "text", text: `${header}
|
|
939
|
+
${formatted}
|
|
940
|
+
${footer}` }]
|
|
941
|
+
};
|
|
942
|
+
}
|
|
943
|
+
);
|
|
944
|
+
}
|
|
945
|
+
|
|
946
|
+
// src/tools/labels.ts
|
|
947
|
+
import { z as z2 } from "zod";
|
|
948
|
+
function registerLabelTools(server2) {
|
|
949
|
+
server2.registerTool(
|
|
950
|
+
"list-labels",
|
|
951
|
+
{
|
|
952
|
+
title: "Browse Labels",
|
|
953
|
+
description: "List all workspace labels with their groups and hierarchy. Labels can be applied to any entry across any collection for cross-domain filtering. Similar to labels in Linear or GitHub.",
|
|
954
|
+
annotations: { readOnlyHint: true }
|
|
955
|
+
},
|
|
956
|
+
async () => {
|
|
957
|
+
const labels = await mcpQuery("kb.listLabels");
|
|
958
|
+
if (labels.length === 0) {
|
|
959
|
+
return { content: [{ type: "text", text: "No labels defined in this workspace yet." }] };
|
|
960
|
+
}
|
|
961
|
+
const groups = labels.filter((l) => l.isGroup);
|
|
962
|
+
const ungrouped = labels.filter((l) => !l.isGroup && !l.parentId);
|
|
963
|
+
const children = (parentId) => labels.filter((l) => l.parentId === parentId);
|
|
964
|
+
const lines = ["# Workspace Labels"];
|
|
965
|
+
for (const group of groups) {
|
|
966
|
+
lines.push(`
|
|
967
|
+
## ${group.name}`);
|
|
968
|
+
if (group.description) lines.push(`_${group.description}_`);
|
|
969
|
+
for (const child of children(group._id)) {
|
|
970
|
+
const color = child.color ? ` ${child.color}` : "";
|
|
971
|
+
lines.push(` - \`${child.slug}\` ${child.name}${color}`);
|
|
972
|
+
}
|
|
973
|
+
}
|
|
974
|
+
if (ungrouped.length > 0) {
|
|
975
|
+
lines.push("\n## Ungrouped");
|
|
976
|
+
for (const label of ungrouped) {
|
|
977
|
+
const color = label.color ? ` ${label.color}` : "";
|
|
978
|
+
lines.push(`- \`${label.slug}\` ${label.name}${color}${label.description ? ` \u2014 _${label.description}_` : ""}`);
|
|
979
|
+
}
|
|
980
|
+
}
|
|
981
|
+
return {
|
|
982
|
+
content: [{ type: "text", text: lines.join("\n") }]
|
|
983
|
+
};
|
|
984
|
+
}
|
|
985
|
+
);
|
|
986
|
+
server2.registerTool(
|
|
987
|
+
"manage-labels",
|
|
988
|
+
{
|
|
989
|
+
title: "Manage Labels",
|
|
990
|
+
description: "Create, update, or delete a workspace label. Labels support hierarchy (groups with children). Use list-labels first to see what exists.",
|
|
991
|
+
inputSchema: {
|
|
992
|
+
action: z2.enum(["create", "update", "delete"]).describe("What to do"),
|
|
993
|
+
slug: z2.string().describe("Label slug (machine name), e.g. 'p1-critical', 'needs-review'"),
|
|
994
|
+
name: z2.string().optional().describe("Display name (required for create)"),
|
|
995
|
+
color: z2.string().optional().describe("Hex color, e.g. '#ef4444'"),
|
|
996
|
+
description: z2.string().optional().describe("What this label means"),
|
|
997
|
+
parentSlug: z2.string().optional().describe("Parent group slug for label hierarchy"),
|
|
998
|
+
isGroup: z2.boolean().optional().describe("True if this is a group container, not a taggable label"),
|
|
999
|
+
order: z2.number().optional().describe("Sort order within its group")
|
|
1000
|
+
}
|
|
1001
|
+
},
|
|
1002
|
+
async ({ action, slug, name, color, description, parentSlug, isGroup, order }) => {
|
|
1003
|
+
if (action === "create") {
|
|
1004
|
+
if (!name) {
|
|
1005
|
+
return { content: [{ type: "text", text: "Cannot create a label without a name." }] };
|
|
1006
|
+
}
|
|
1007
|
+
let parentId;
|
|
1008
|
+
if (parentSlug) {
|
|
1009
|
+
const labels = await mcpQuery("kb.listLabels");
|
|
1010
|
+
const parent = labels.find((l) => l.slug === parentSlug);
|
|
1011
|
+
if (!parent) {
|
|
1012
|
+
return { content: [{ type: "text", text: `Parent label \`${parentSlug}\` not found. Use list-labels to see available groups.` }] };
|
|
1013
|
+
}
|
|
1014
|
+
parentId = parent._id;
|
|
1015
|
+
}
|
|
1016
|
+
await mcpMutation("kb.createLabel", { slug, name, color, description, parentId, isGroup, order });
|
|
1017
|
+
return { content: [{ type: "text", text: `# Label Created
|
|
1018
|
+
|
|
1019
|
+
**${name}** (\`${slug}\`)` }] };
|
|
1020
|
+
}
|
|
1021
|
+
if (action === "update") {
|
|
1022
|
+
await mcpMutation("kb.updateLabel", { slug, name, color, description, isGroup, order });
|
|
1023
|
+
return { content: [{ type: "text", text: `# Label Updated
|
|
1024
|
+
|
|
1025
|
+
\`${slug}\` has been updated.` }] };
|
|
1026
|
+
}
|
|
1027
|
+
if (action === "delete") {
|
|
1028
|
+
await mcpMutation("kb.deleteLabel", { slug });
|
|
1029
|
+
return { content: [{ type: "text", text: `# Label Deleted
|
|
1030
|
+
|
|
1031
|
+
\`${slug}\` removed from all entries and deleted.` }] };
|
|
1032
|
+
}
|
|
1033
|
+
return { content: [{ type: "text", text: "Unknown action." }] };
|
|
1034
|
+
}
|
|
1035
|
+
);
|
|
1036
|
+
server2.registerTool(
|
|
1037
|
+
"label-entry",
|
|
1038
|
+
{
|
|
1039
|
+
title: "Tag Entry with Label",
|
|
1040
|
+
description: "Apply or remove a label from a knowledge entry. Labels work across all collections for cross-domain filtering. Use list-labels to see available label slugs.",
|
|
1041
|
+
inputSchema: {
|
|
1042
|
+
action: z2.enum(["apply", "remove"]).describe("Apply or remove the label"),
|
|
1043
|
+
entryId: z2.string().describe("Entry ID, e.g. 'T-SUPPLIER', 'EVT-workspace_created'"),
|
|
1044
|
+
label: z2.string().describe("Label slug to apply/remove")
|
|
1045
|
+
}
|
|
1046
|
+
},
|
|
1047
|
+
async ({ action, entryId, label }) => {
|
|
1048
|
+
if (action === "apply") {
|
|
1049
|
+
await mcpMutation("kb.applyLabel", { entryId, labelSlug: label });
|
|
1050
|
+
return { content: [{ type: "text", text: `Label \`${label}\` applied to **${entryId}**.` }] };
|
|
1051
|
+
}
|
|
1052
|
+
await mcpMutation("kb.removeLabel", { entryId, labelSlug: label });
|
|
1053
|
+
return { content: [{ type: "text", text: `Label \`${label}\` removed from **${entryId}**.` }] };
|
|
1054
|
+
}
|
|
1055
|
+
);
|
|
1056
|
+
}
|
|
1057
|
+
|
|
1058
|
+
// src/tools/health.ts
|
|
1059
|
+
import { z as z3 } from "zod";
|
|
1060
|
+
var CALL_CATEGORIES = {
|
|
1061
|
+
"kb.getEntry": "read",
|
|
1062
|
+
"kb.listEntries": "read",
|
|
1063
|
+
"kb.listEntryHistory": "read",
|
|
1064
|
+
"kb.listEntryRelations": "read",
|
|
1065
|
+
"kb.listEntriesByLabel": "read",
|
|
1066
|
+
"kb.searchEntries": "search",
|
|
1067
|
+
"kb.createEntry": "write",
|
|
1068
|
+
"kb.updateEntry": "write",
|
|
1069
|
+
"kb.createEntryRelation": "write",
|
|
1070
|
+
"kb.applyLabel": "label",
|
|
1071
|
+
"kb.removeLabel": "label",
|
|
1072
|
+
"kb.createLabel": "label",
|
|
1073
|
+
"kb.updateLabel": "label",
|
|
1074
|
+
"kb.deleteLabel": "label",
|
|
1075
|
+
"kb.listCollections": "meta",
|
|
1076
|
+
"kb.getCollection": "meta",
|
|
1077
|
+
"kb.listLabels": "meta",
|
|
1078
|
+
"resolveWorkspace": "meta"
|
|
1079
|
+
};
|
|
1080
|
+
function categorize(fn) {
|
|
1081
|
+
return CALL_CATEGORIES[fn] ?? "meta";
|
|
1082
|
+
}
|
|
1083
|
+
function formatDuration(ms) {
|
|
1084
|
+
if (ms < 6e4) return `${Math.round(ms / 1e3)}s`;
|
|
1085
|
+
const mins = Math.floor(ms / 6e4);
|
|
1086
|
+
const secs = Math.round(ms % 6e4 / 1e3);
|
|
1087
|
+
return `${mins}m ${secs}s`;
|
|
1088
|
+
}
|
|
1089
|
+
function buildSessionSummary(log2) {
|
|
1090
|
+
if (log2.length === 0) return "";
|
|
1091
|
+
const byCategory = /* @__PURE__ */ new Map();
|
|
1092
|
+
let errorCount = 0;
|
|
1093
|
+
let writeCreates = 0;
|
|
1094
|
+
let writeUpdates = 0;
|
|
1095
|
+
for (const entry of log2) {
|
|
1096
|
+
const cat = categorize(entry.fn);
|
|
1097
|
+
if (!byCategory.has(cat)) byCategory.set(cat, /* @__PURE__ */ new Map());
|
|
1098
|
+
const fnCounts = byCategory.get(cat);
|
|
1099
|
+
fnCounts.set(entry.fn, (fnCounts.get(entry.fn) ?? 0) + 1);
|
|
1100
|
+
if (entry.status === "error") errorCount++;
|
|
1101
|
+
if (entry.fn === "kb.createEntry" && entry.status === "ok") writeCreates++;
|
|
1102
|
+
if (entry.fn === "kb.updateEntry" && entry.status === "ok") writeUpdates++;
|
|
1103
|
+
}
|
|
1104
|
+
const firstTs = new Date(log2[0].ts).getTime();
|
|
1105
|
+
const lastTs = new Date(log2[log2.length - 1].ts).getTime();
|
|
1106
|
+
const duration = formatDuration(lastTs - firstTs);
|
|
1107
|
+
const lines = [`# Session Summary (${duration})
|
|
1108
|
+
`];
|
|
1109
|
+
const categoryLabels = [
|
|
1110
|
+
["read", "Reads"],
|
|
1111
|
+
["search", "Searches"],
|
|
1112
|
+
["write", "Writes"],
|
|
1113
|
+
["label", "Labels"],
|
|
1114
|
+
["meta", "Meta"]
|
|
1115
|
+
];
|
|
1116
|
+
for (const [cat, label] of categoryLabels) {
|
|
1117
|
+
const fnCounts = byCategory.get(cat);
|
|
1118
|
+
if (!fnCounts || fnCounts.size === 0) continue;
|
|
1119
|
+
const total = [...fnCounts.values()].reduce((a, b) => a + b, 0);
|
|
1120
|
+
const detail = [...fnCounts.entries()].sort((a, b) => b[1] - a[1]).map(([fn, count]) => `${fn.replace("kb.", "")} x${count}`).join(", ");
|
|
1121
|
+
lines.push(`- **${label}:** ${total} call${total === 1 ? "" : "s"} (${detail})`);
|
|
1122
|
+
}
|
|
1123
|
+
lines.push(`- **Errors:** ${errorCount}`);
|
|
1124
|
+
if (writeCreates > 0 || writeUpdates > 0) {
|
|
1125
|
+
lines.push("");
|
|
1126
|
+
lines.push("## Knowledge Contribution");
|
|
1127
|
+
if (writeCreates > 0) lines.push(`- ${writeCreates} entr${writeCreates === 1 ? "y" : "ies"} created`);
|
|
1128
|
+
if (writeUpdates > 0) lines.push(`- ${writeUpdates} entr${writeUpdates === 1 ? "y" : "ies"} updated`);
|
|
1129
|
+
}
|
|
1130
|
+
return lines.join("\n");
|
|
1131
|
+
}
|
|
1132
|
+
function registerHealthTools(server2) {
|
|
1133
|
+
server2.registerTool(
|
|
1134
|
+
"health",
|
|
1135
|
+
{
|
|
1136
|
+
title: "Health Check",
|
|
1137
|
+
description: "Verify that ProductBrain is running and can reach its backend. Returns workspace status, collection count, entry count, and latency. Use this to confirm connectivity before doing real work.",
|
|
1138
|
+
annotations: { readOnlyHint: true }
|
|
1139
|
+
},
|
|
1140
|
+
async () => {
|
|
1141
|
+
const start = Date.now();
|
|
1142
|
+
const errors = [];
|
|
1143
|
+
let workspaceId2;
|
|
1144
|
+
try {
|
|
1145
|
+
workspaceId2 = await getWorkspaceId();
|
|
1146
|
+
} catch (e) {
|
|
1147
|
+
errors.push(`Workspace resolution failed: ${e.message}`);
|
|
1148
|
+
}
|
|
1149
|
+
let collections = [];
|
|
1150
|
+
try {
|
|
1151
|
+
collections = await mcpQuery("kb.listCollections");
|
|
1152
|
+
} catch (e) {
|
|
1153
|
+
errors.push(`Collection fetch failed: ${e.message}`);
|
|
1154
|
+
}
|
|
1155
|
+
let totalEntries = 0;
|
|
1156
|
+
if (collections.length > 0) {
|
|
1157
|
+
try {
|
|
1158
|
+
const entries = await mcpQuery("kb.listEntries", {});
|
|
1159
|
+
totalEntries = entries.length;
|
|
1160
|
+
} catch (e) {
|
|
1161
|
+
errors.push(`Entry count failed: ${e.message}`);
|
|
1162
|
+
}
|
|
1163
|
+
}
|
|
1164
|
+
const durationMs = Date.now() - start;
|
|
1165
|
+
const healthy = errors.length === 0;
|
|
1166
|
+
const lines = [
|
|
1167
|
+
`# ${healthy ? "Healthy" : "Degraded"}`,
|
|
1168
|
+
"",
|
|
1169
|
+
`**Workspace:** ${workspaceId2 ?? "unresolved"}`,
|
|
1170
|
+
`**Collections:** ${collections.length}`,
|
|
1171
|
+
`**Entries:** ${totalEntries}`,
|
|
1172
|
+
`**Latency:** ${durationMs}ms`
|
|
1173
|
+
];
|
|
1174
|
+
if (errors.length > 0) {
|
|
1175
|
+
lines.push("", "## Errors");
|
|
1176
|
+
for (const err of errors) {
|
|
1177
|
+
lines.push(`- ${err}`);
|
|
1178
|
+
}
|
|
1179
|
+
}
|
|
1180
|
+
return { content: [{ type: "text", text: lines.join("\n") }] };
|
|
1181
|
+
}
|
|
1182
|
+
);
|
|
1183
|
+
server2.registerTool(
|
|
1184
|
+
"mcp-audit",
|
|
1185
|
+
{
|
|
1186
|
+
title: "Session Audit Log",
|
|
1187
|
+
description: "Show a session summary (reads, writes, searches, contributions) and the last N backend calls. Useful for debugging, tracing tool behavior, and seeing what you contributed to the knowledge base.",
|
|
1188
|
+
inputSchema: {
|
|
1189
|
+
limit: z3.number().min(1).max(50).default(20).describe("How many recent calls to show (max 50)")
|
|
1190
|
+
},
|
|
1191
|
+
annotations: { readOnlyHint: true }
|
|
1192
|
+
},
|
|
1193
|
+
async ({ limit }) => {
|
|
1194
|
+
const log2 = getAuditLog();
|
|
1195
|
+
const recent = log2.slice(-limit);
|
|
1196
|
+
if (recent.length === 0) {
|
|
1197
|
+
return { content: [{ type: "text", text: "No calls recorded yet this session." }] };
|
|
1198
|
+
}
|
|
1199
|
+
const summary = buildSessionSummary(log2);
|
|
1200
|
+
const logLines = [`# Audit Log (last ${recent.length} of ${log2.length} total)
|
|
1201
|
+
`];
|
|
1202
|
+
for (const entry of recent) {
|
|
1203
|
+
const icon = entry.status === "ok" ? "\u2713" : "\u2717";
|
|
1204
|
+
const errPart = entry.error ? ` \u2014 ${entry.error}` : "";
|
|
1205
|
+
logLines.push(`${icon} \`${entry.fn}\` ${entry.durationMs}ms ${entry.status}${errPart}`);
|
|
1206
|
+
}
|
|
1207
|
+
return {
|
|
1208
|
+
content: [{ type: "text", text: `${summary}
|
|
1209
|
+
|
|
1210
|
+
---
|
|
1211
|
+
|
|
1212
|
+
${logLines.join("\n")}` }]
|
|
1213
|
+
};
|
|
1214
|
+
}
|
|
1215
|
+
);
|
|
1216
|
+
}
|
|
1217
|
+
|
|
1218
|
+
// src/tools/verify.ts
|
|
1219
|
+
import { existsSync, readFileSync } from "fs";
|
|
1220
|
+
import { resolve } from "path";
|
|
1221
|
+
import { z as z4 } from "zod";
|
|
1222
|
+
function resolveProjectRoot() {
|
|
1223
|
+
const candidates = [
|
|
1224
|
+
process.env.WORKSPACE_PATH,
|
|
1225
|
+
process.cwd(),
|
|
1226
|
+
resolve(process.cwd(), "..")
|
|
1227
|
+
].filter(Boolean);
|
|
1228
|
+
for (const dir of candidates) {
|
|
1229
|
+
const resolved = resolve(dir);
|
|
1230
|
+
if (existsSync(resolve(resolved, "convex/schema.ts"))) return resolved;
|
|
1231
|
+
}
|
|
1232
|
+
return null;
|
|
1233
|
+
}
|
|
1234
|
+
function parseConvexSchema(schemaPath) {
|
|
1235
|
+
const content = readFileSync(schemaPath, "utf-8");
|
|
1236
|
+
const tables = /* @__PURE__ */ new Map();
|
|
1237
|
+
let currentTable = null;
|
|
1238
|
+
for (const line of content.split("\n")) {
|
|
1239
|
+
const tableMatch = line.match(/^\t(\w+):\s*defineTable\(/);
|
|
1240
|
+
if (tableMatch) {
|
|
1241
|
+
currentTable = tableMatch[1];
|
|
1242
|
+
tables.set(currentTable, /* @__PURE__ */ new Set());
|
|
1243
|
+
continue;
|
|
1244
|
+
}
|
|
1245
|
+
if (currentTable && /^\t[}\)]/.test(line) && !/^\t\t/.test(line)) {
|
|
1246
|
+
currentTable = null;
|
|
1247
|
+
continue;
|
|
1248
|
+
}
|
|
1249
|
+
if (currentTable) {
|
|
1250
|
+
const fieldMatch = line.match(/^\t\t(\w+):\s*v\./);
|
|
1251
|
+
if (fieldMatch) tables.get(currentTable).add(fieldMatch[1]);
|
|
1252
|
+
}
|
|
1253
|
+
}
|
|
1254
|
+
return tables;
|
|
1255
|
+
}
|
|
1256
|
+
function cleanFieldRef(field) {
|
|
1257
|
+
return field.replace(/\s*\(.*\)\s*$/, "").replace(/\s*=\s*.*$/, "").trim();
|
|
1258
|
+
}
|
|
1259
|
+
function splitMultiRefs(field) {
|
|
1260
|
+
if (field.includes(" + ")) return field.split(/\s*\+\s*/);
|
|
1261
|
+
return [field];
|
|
1262
|
+
}
|
|
1263
|
+
var FILE_EXT_RE = /\.(ts|js|svelte|json|css|md|jsx|tsx|mjs|cjs)(?:\s|$)/i;
|
|
1264
|
+
function classifyRef(cleaned) {
|
|
1265
|
+
if (cleaned.includes("/") || FILE_EXT_RE.test(cleaned) || /^\.\w+/.test(cleaned)) {
|
|
1266
|
+
return "file";
|
|
1267
|
+
}
|
|
1268
|
+
if (/^\w+\.\w+$/.test(cleaned)) return "schema";
|
|
1269
|
+
if (/^\w+\s+table$/i.test(cleaned)) return "schema";
|
|
1270
|
+
return "conceptual";
|
|
1271
|
+
}
|
|
1272
|
+
function checkFileRef(ref, root) {
|
|
1273
|
+
const filePart = ref.split(/\s+/)[0];
|
|
1274
|
+
const fullPath = resolve(root, filePart);
|
|
1275
|
+
if (existsSync(fullPath)) return { result: "verified", reason: "exists" };
|
|
1276
|
+
return { result: "drifted", reason: `not found: ${filePart}` };
|
|
1277
|
+
}
|
|
1278
|
+
function checkSchemaRef(ref, schema) {
|
|
1279
|
+
const tableOnlyMatch = ref.match(/^(\w+)\s+table$/i);
|
|
1280
|
+
if (tableOnlyMatch) {
|
|
1281
|
+
const table = tableOnlyMatch[1];
|
|
1282
|
+
if (schema.has(table)) return { result: "verified", reason: `table "${table}" exists` };
|
|
1283
|
+
return { result: "drifted", reason: `table "${table}" not found in schema` };
|
|
1284
|
+
}
|
|
1285
|
+
const dotIdx = ref.indexOf(".");
|
|
1286
|
+
if (dotIdx > 0) {
|
|
1287
|
+
const table = ref.slice(0, dotIdx);
|
|
1288
|
+
const field = ref.slice(dotIdx + 1);
|
|
1289
|
+
if (!schema.has(table)) return { result: "drifted", reason: `table "${table}" not found in schema` };
|
|
1290
|
+
if (!schema.get(table).has(field)) return { result: "drifted", reason: `field "${field}" not found in table "${table}"` };
|
|
1291
|
+
return { result: "verified", reason: `${table}.${field} exists` };
|
|
1292
|
+
}
|
|
1293
|
+
return { result: "unverifiable", reason: "could not parse schema reference" };
|
|
1294
|
+
}
|
|
1295
|
+
function formatTrustReport(collection, entryCount, mappings, refs, fixes, mode, schemaTableCount, projectRoot) {
|
|
1296
|
+
const verified = mappings.filter((c) => c.result === "verified").length;
|
|
1297
|
+
const drifted = mappings.filter((c) => c.result === "drifted").length;
|
|
1298
|
+
const unverifiable = mappings.filter((c) => c.result === "unverifiable").length;
|
|
1299
|
+
const refsValid = refs.filter((c) => c.found).length;
|
|
1300
|
+
const refsBroken = refs.filter((c) => !c.found).length;
|
|
1301
|
+
const totalChecks = mappings.length + refs.length;
|
|
1302
|
+
const totalPassed = verified + refsValid;
|
|
1303
|
+
const trustScore = totalChecks > 0 ? Math.round(totalPassed / totalChecks * 100) : 100;
|
|
1304
|
+
const lines = [
|
|
1305
|
+
`# Trust Report: ${collection} (${entryCount} entries scanned)`,
|
|
1306
|
+
""
|
|
1307
|
+
];
|
|
1308
|
+
if (mappings.length > 0) {
|
|
1309
|
+
lines.push(
|
|
1310
|
+
"## Code Mapping Verification",
|
|
1311
|
+
`- ${mappings.length} mappings checked`,
|
|
1312
|
+
`- ${verified} verified (${Math.round(verified / mappings.length * 100)}%)`,
|
|
1313
|
+
`- ${drifted} drifted (file/schema not found)`,
|
|
1314
|
+
`- ${unverifiable} unverifiable (conceptual \u2014 skipped)`,
|
|
1315
|
+
""
|
|
1316
|
+
);
|
|
1317
|
+
}
|
|
1318
|
+
if (drifted > 0) {
|
|
1319
|
+
lines.push("### Drifted Mappings");
|
|
1320
|
+
for (const mc of mappings.filter((c) => c.result === "drifted")) {
|
|
1321
|
+
lines.push(`- **${mc.entryId}** (${mc.entryName}): \`${mc.field}\` \u2014 ${mc.reason}`);
|
|
1322
|
+
}
|
|
1323
|
+
lines.push("");
|
|
1324
|
+
}
|
|
1325
|
+
if (unverifiable > 0) {
|
|
1326
|
+
lines.push("### Unverifiable (Conceptual)");
|
|
1327
|
+
for (const mc of mappings.filter((c) => c.result === "unverifiable")) {
|
|
1328
|
+
lines.push(`- **${mc.entryId}** (${mc.entryName}): \`${mc.field}\``);
|
|
1329
|
+
}
|
|
1330
|
+
lines.push("");
|
|
1331
|
+
}
|
|
1332
|
+
if (refs.length > 0) {
|
|
1333
|
+
lines.push(
|
|
1334
|
+
"## Cross-Reference Verification",
|
|
1335
|
+
`- ${refs.length} references checked`,
|
|
1336
|
+
`- ${refsValid} valid (${refs.length > 0 ? Math.round(refsValid / refs.length * 100) : 0}%)`,
|
|
1337
|
+
`- ${refsBroken} broken`,
|
|
1338
|
+
""
|
|
1339
|
+
);
|
|
1340
|
+
}
|
|
1341
|
+
if (refsBroken > 0) {
|
|
1342
|
+
lines.push("### Broken References");
|
|
1343
|
+
for (const rc of refs.filter((c) => !c.found)) {
|
|
1344
|
+
lines.push(`- **${rc.entryId}** (${rc.entryName}): relatedRules \`${rc.refValue}\` \u2014 entry not found`);
|
|
1345
|
+
}
|
|
1346
|
+
lines.push("");
|
|
1347
|
+
}
|
|
1348
|
+
lines.push(`## Trust Score: ${trustScore}% (${totalPassed} of ${totalChecks} checks passed)`);
|
|
1349
|
+
if (mode === "fix" && fixes.length > 0) {
|
|
1350
|
+
lines.push(
|
|
1351
|
+
"",
|
|
1352
|
+
"## Applied Fixes",
|
|
1353
|
+
`Updated codeMapping status from \`aligned\` \u2192 \`drifted\` on ${fixes.length} entr${fixes.length === 1 ? "y" : "ies"}:`
|
|
1354
|
+
);
|
|
1355
|
+
for (const eid of fixes) lines.push(`- ${eid}`);
|
|
1356
|
+
} else if (mode === "report" && drifted > 0) {
|
|
1357
|
+
const fixable = mappings.filter((c) => c.result === "drifted" && c.currentStatus === "aligned").length;
|
|
1358
|
+
if (fixable > 0) {
|
|
1359
|
+
lines.push("", `_${fixable} mapping(s) marked "aligned" but actually drifted. Run with mode="fix" to update._`);
|
|
1360
|
+
}
|
|
1361
|
+
}
|
|
1362
|
+
lines.push("", "---", `_Schema: ${schemaTableCount} tables parsed from convex/schema.ts. Project root: ${projectRoot}_`);
|
|
1363
|
+
return lines.join("\n");
|
|
1364
|
+
}
|
|
1365
|
+
function registerVerifyTools(server2) {
|
|
1366
|
+
server2.registerTool(
|
|
1367
|
+
"verify",
|
|
1368
|
+
{
|
|
1369
|
+
title: "Verify Knowledge Base",
|
|
1370
|
+
description: "Verify knowledge entries against the actual codebase. Checks glossary code mappings (do referenced files and schema fields still exist?) and validates cross-references (do relatedRules point to real entries?). Produces a trust report with a trust score. Use mode='fix' to auto-update drifted codeMapping statuses.",
|
|
1371
|
+
inputSchema: {
|
|
1372
|
+
collection: z4.string().default("glossary").describe("Collection slug to verify (default: glossary)"),
|
|
1373
|
+
mode: z4.enum(["report", "fix"]).default("report").describe("'report' = read-only trust report. 'fix' = also update drifted codeMapping statuses.")
|
|
1374
|
+
},
|
|
1375
|
+
annotations: { readOnlyHint: false }
|
|
1376
|
+
},
|
|
1377
|
+
async ({ collection, mode }) => {
|
|
1378
|
+
const projectRoot = resolveProjectRoot();
|
|
1379
|
+
if (!projectRoot) {
|
|
1380
|
+
return {
|
|
1381
|
+
content: [{
|
|
1382
|
+
type: "text",
|
|
1383
|
+
text: "# Verification Failed\n\nCannot find project root (looked for `convex/schema.ts` in cwd and parent directory).\n\nSet `WORKSPACE_PATH` in `.env.mcp` to the absolute path of the ProductBrain project root."
|
|
1384
|
+
}]
|
|
1385
|
+
};
|
|
1386
|
+
}
|
|
1387
|
+
const schema = parseConvexSchema(resolve(projectRoot, "convex/schema.ts"));
|
|
1388
|
+
await server2.sendLoggingMessage({
|
|
1389
|
+
level: "info",
|
|
1390
|
+
data: `Verifying "${collection}" against ${schema.size} schema tables at ${projectRoot}`,
|
|
1391
|
+
logger: "product-os"
|
|
1392
|
+
});
|
|
1393
|
+
const scopedEntries = await mcpQuery("kb.listEntries", { collectionSlug: collection });
|
|
1394
|
+
if (scopedEntries.length === 0) {
|
|
1395
|
+
return {
|
|
1396
|
+
content: [{ type: "text", text: `No entries found in \`${collection}\`. Nothing to verify.` }]
|
|
1397
|
+
};
|
|
1398
|
+
}
|
|
1399
|
+
let allEntryIds;
|
|
1400
|
+
try {
|
|
1401
|
+
const allEntries = await mcpQuery("kb.listEntries", {});
|
|
1402
|
+
allEntryIds = new Set(allEntries.map((e) => e.entryId).filter(Boolean));
|
|
1403
|
+
} catch {
|
|
1404
|
+
allEntryIds = new Set(scopedEntries.map((e) => e.entryId).filter(Boolean));
|
|
1405
|
+
}
|
|
1406
|
+
const mappingChecks = [];
|
|
1407
|
+
const refChecks = [];
|
|
1408
|
+
for (const entry of scopedEntries) {
|
|
1409
|
+
const eid = entry.entryId ?? entry.name;
|
|
1410
|
+
const ename = entry.name;
|
|
1411
|
+
const codeMappings = entry.data?.codeMapping ?? [];
|
|
1412
|
+
for (const cm of codeMappings) {
|
|
1413
|
+
const rawField = cm.field ?? "";
|
|
1414
|
+
for (const rawRef of splitMultiRefs(rawField)) {
|
|
1415
|
+
const cleaned = cleanFieldRef(rawRef);
|
|
1416
|
+
if (!cleaned) continue;
|
|
1417
|
+
const kind = classifyRef(cleaned);
|
|
1418
|
+
let result;
|
|
1419
|
+
let reason;
|
|
1420
|
+
if (kind === "file") {
|
|
1421
|
+
({ result, reason } = checkFileRef(cleaned, projectRoot));
|
|
1422
|
+
} else if (kind === "schema") {
|
|
1423
|
+
({ result, reason } = checkSchemaRef(cleaned, schema));
|
|
1424
|
+
} else {
|
|
1425
|
+
result = "unverifiable";
|
|
1426
|
+
reason = "conceptual reference";
|
|
1427
|
+
}
|
|
1428
|
+
mappingChecks.push({
|
|
1429
|
+
entryId: eid,
|
|
1430
|
+
entryName: ename,
|
|
1431
|
+
field: rawRef.trim(),
|
|
1432
|
+
kind,
|
|
1433
|
+
result,
|
|
1434
|
+
reason,
|
|
1435
|
+
currentStatus: cm.status ?? "unknown"
|
|
1436
|
+
});
|
|
1437
|
+
}
|
|
1438
|
+
}
|
|
1439
|
+
const MAX_CROSS_REFS = 50;
|
|
1440
|
+
const relatedRules = entry.data?.relatedRules ?? [];
|
|
1441
|
+
for (const ruleId of relatedRules) {
|
|
1442
|
+
if (refChecks.length >= MAX_CROSS_REFS) break;
|
|
1443
|
+
refChecks.push({
|
|
1444
|
+
entryId: eid,
|
|
1445
|
+
entryName: ename,
|
|
1446
|
+
refValue: ruleId,
|
|
1447
|
+
found: allEntryIds.has(ruleId)
|
|
1448
|
+
});
|
|
1449
|
+
}
|
|
1450
|
+
}
|
|
1451
|
+
const fixes = [];
|
|
1452
|
+
if (mode === "fix") {
|
|
1453
|
+
const driftedByEntry = /* @__PURE__ */ new Map();
|
|
1454
|
+
for (const mc of mappingChecks) {
|
|
1455
|
+
if (mc.result === "drifted" && mc.currentStatus === "aligned") {
|
|
1456
|
+
if (!driftedByEntry.has(mc.entryId)) driftedByEntry.set(mc.entryId, /* @__PURE__ */ new Set());
|
|
1457
|
+
driftedByEntry.get(mc.entryId).add(mc.field);
|
|
1458
|
+
}
|
|
1459
|
+
}
|
|
1460
|
+
for (const [eid, driftedFields] of driftedByEntry) {
|
|
1461
|
+
const entry = scopedEntries.find((e) => (e.entryId ?? e.name) === eid);
|
|
1462
|
+
if (!entry?.entryId) continue;
|
|
1463
|
+
const updated = (entry.data?.codeMapping ?? []).map(
|
|
1464
|
+
(cm) => cm.status === "aligned" && driftedFields.has(cm.field) ? { ...cm, status: "drifted" } : cm
|
|
1465
|
+
);
|
|
1466
|
+
await mcpMutation("kb.updateEntry", {
|
|
1467
|
+
entryId: entry.entryId,
|
|
1468
|
+
data: { codeMapping: updated }
|
|
1469
|
+
});
|
|
1470
|
+
fixes.push(entry.entryId);
|
|
1471
|
+
}
|
|
1472
|
+
}
|
|
1473
|
+
const report = formatTrustReport(
|
|
1474
|
+
collection,
|
|
1475
|
+
scopedEntries.length,
|
|
1476
|
+
mappingChecks,
|
|
1477
|
+
refChecks,
|
|
1478
|
+
fixes,
|
|
1479
|
+
mode,
|
|
1480
|
+
schema.size,
|
|
1481
|
+
projectRoot
|
|
1482
|
+
);
|
|
1483
|
+
return { content: [{ type: "text", text: report }] };
|
|
1484
|
+
}
|
|
1485
|
+
);
|
|
1486
|
+
}
|
|
1487
|
+
|
|
1488
|
+
// src/tools/smart-capture.ts
|
|
1489
|
+
import { z as z5 } from "zod";
|
|
1490
|
+
var AREA_KEYWORDS = {
|
|
1491
|
+
"Architecture": ["convex", "schema", "database", "migration", "api", "backend", "infrastructure", "scaling", "performance"],
|
|
1492
|
+
"Knowledge Base": ["knowledge", "glossary", "entry", "collection", "terminology", "drift", "graph"],
|
|
1493
|
+
"AI & MCP Integration": ["mcp", "ai", "cursor", "agent", "tool", "llm", "prompt", "context"],
|
|
1494
|
+
"Developer Experience": ["dx", "developer", "ide", "workflow", "friction", "ceremony"],
|
|
1495
|
+
"Governance & Decision-Making": ["governance", "decision", "rule", "policy", "compliance", "approval"],
|
|
1496
|
+
"Analytics & Tracking": ["analytics", "posthog", "tracking", "event", "metric", "funnel"],
|
|
1497
|
+
"Security": ["security", "auth", "api key", "permission", "access", "token"]
|
|
1498
|
+
};
|
|
1499
|
+
function inferArea(text) {
|
|
1500
|
+
const lower = text.toLowerCase();
|
|
1501
|
+
let bestArea = "";
|
|
1502
|
+
let bestScore = 0;
|
|
1503
|
+
for (const [area, keywords] of Object.entries(AREA_KEYWORDS)) {
|
|
1504
|
+
const score = keywords.filter((kw) => lower.includes(kw)).length;
|
|
1505
|
+
if (score > bestScore) {
|
|
1506
|
+
bestScore = score;
|
|
1507
|
+
bestArea = area;
|
|
1508
|
+
}
|
|
1509
|
+
}
|
|
1510
|
+
return bestArea;
|
|
1511
|
+
}
|
|
1512
|
+
function inferDomain(text) {
|
|
1513
|
+
return inferArea(text) || "";
|
|
1514
|
+
}
|
|
1515
|
+
var COMMON_CHECKS = {
|
|
1516
|
+
clearName: {
|
|
1517
|
+
id: "clear-name",
|
|
1518
|
+
label: "Clear, specific name (not vague)",
|
|
1519
|
+
check: (ctx) => ctx.name.length > 10 && !["new tension", "new entry", "untitled", "test"].includes(ctx.name.toLowerCase()),
|
|
1520
|
+
suggestion: () => "Rename to something specific \u2014 describe the actual problem or concept."
|
|
1521
|
+
},
|
|
1522
|
+
hasDescription: {
|
|
1523
|
+
id: "has-description",
|
|
1524
|
+
label: "Description provided (>50 chars)",
|
|
1525
|
+
check: (ctx) => ctx.description.length > 50,
|
|
1526
|
+
suggestion: () => "Add a fuller description explaining context and impact."
|
|
1527
|
+
},
|
|
1528
|
+
hasRelations: {
|
|
1529
|
+
id: "has-relations",
|
|
1530
|
+
label: "At least 1 relation created",
|
|
1531
|
+
check: (ctx) => ctx.linksCreated.length >= 1,
|
|
1532
|
+
suggestion: () => "Use `suggest-links` and `relate-entries` to connect this entry to related knowledge."
|
|
1533
|
+
},
|
|
1534
|
+
diverseRelations: {
|
|
1535
|
+
id: "diverse-relations",
|
|
1536
|
+
label: "Relations span multiple collections",
|
|
1537
|
+
check: (ctx) => {
|
|
1538
|
+
const colls = new Set(ctx.linksCreated.map((l) => l.targetCollection));
|
|
1539
|
+
return colls.size >= 2;
|
|
1540
|
+
},
|
|
1541
|
+
suggestion: () => "Try linking to entries in different collections (glossary, business-rules, strategy)."
|
|
1542
|
+
}
|
|
1543
|
+
};
|
|
1544
|
+
var PROFILES = /* @__PURE__ */ new Map([
|
|
1545
|
+
["tensions", {
|
|
1546
|
+
idPrefix: "TEN",
|
|
1547
|
+
governedDraft: false,
|
|
1548
|
+
descriptionField: "description",
|
|
1549
|
+
defaults: [
|
|
1550
|
+
{ key: "priority", value: "medium" },
|
|
1551
|
+
{ key: "date", value: "today" },
|
|
1552
|
+
{ key: "raised", value: "infer" },
|
|
1553
|
+
{ key: "severity", value: "infer" }
|
|
1554
|
+
],
|
|
1555
|
+
recommendedRelationTypes: ["surfaces_tension_in", "references", "belongs_to", "related_to"],
|
|
1556
|
+
inferField: (ctx) => {
|
|
1557
|
+
const fields = {};
|
|
1558
|
+
const text = `${ctx.name} ${ctx.description}`;
|
|
1559
|
+
const area = inferArea(text);
|
|
1560
|
+
if (area) fields.raised = area;
|
|
1561
|
+
if (text.toLowerCase().includes("critical") || text.toLowerCase().includes("blocker")) {
|
|
1562
|
+
fields.severity = "critical";
|
|
1563
|
+
} else if (text.toLowerCase().includes("bottleneck") || text.toLowerCase().includes("scaling") || text.toLowerCase().includes("breaking")) {
|
|
1564
|
+
fields.severity = "high";
|
|
1565
|
+
} else {
|
|
1566
|
+
fields.severity = "medium";
|
|
1567
|
+
}
|
|
1568
|
+
if (area) fields.affectedArea = area;
|
|
1569
|
+
return fields;
|
|
1570
|
+
},
|
|
1571
|
+
qualityChecks: [
|
|
1572
|
+
COMMON_CHECKS.clearName,
|
|
1573
|
+
COMMON_CHECKS.hasDescription,
|
|
1574
|
+
COMMON_CHECKS.hasRelations,
|
|
1575
|
+
{
|
|
1576
|
+
id: "has-severity",
|
|
1577
|
+
label: "Severity specified",
|
|
1578
|
+
check: (ctx) => !!ctx.data.severity && ctx.data.severity !== "",
|
|
1579
|
+
suggestion: (ctx) => {
|
|
1580
|
+
const text = `${ctx.name} ${ctx.description}`.toLowerCase();
|
|
1581
|
+
const inferred = text.includes("critical") ? "critical" : text.includes("bottleneck") ? "high" : "medium";
|
|
1582
|
+
return `Set severity \u2014 suggest: ${inferred} (based on description keywords).`;
|
|
1583
|
+
}
|
|
1584
|
+
},
|
|
1585
|
+
{
|
|
1586
|
+
id: "has-affected-area",
|
|
1587
|
+
label: "Affected area identified",
|
|
1588
|
+
check: (ctx) => !!ctx.data.affectedArea && ctx.data.affectedArea !== "",
|
|
1589
|
+
suggestion: (ctx) => {
|
|
1590
|
+
const area = inferArea(`${ctx.name} ${ctx.description}`);
|
|
1591
|
+
return area ? `Set affectedArea \u2014 suggest: "${area}" (inferred from content).` : "Specify which product area or domain this tension impacts.";
|
|
1592
|
+
}
|
|
1593
|
+
}
|
|
1594
|
+
]
|
|
1595
|
+
}],
|
|
1596
|
+
["business-rules", {
|
|
1597
|
+
idPrefix: "SOS",
|
|
1598
|
+
governedDraft: true,
|
|
1599
|
+
descriptionField: "description",
|
|
1600
|
+
defaults: [
|
|
1601
|
+
{ key: "severity", value: "medium" },
|
|
1602
|
+
{ key: "domain", value: "infer" }
|
|
1603
|
+
],
|
|
1604
|
+
recommendedRelationTypes: ["governs", "references", "conflicts_with", "related_to"],
|
|
1605
|
+
inferField: (ctx) => {
|
|
1606
|
+
const fields = {};
|
|
1607
|
+
const domain = inferDomain(`${ctx.name} ${ctx.description}`);
|
|
1608
|
+
if (domain) fields.domain = domain;
|
|
1609
|
+
return fields;
|
|
1610
|
+
},
|
|
1611
|
+
qualityChecks: [
|
|
1612
|
+
COMMON_CHECKS.clearName,
|
|
1613
|
+
COMMON_CHECKS.hasDescription,
|
|
1614
|
+
COMMON_CHECKS.hasRelations,
|
|
1615
|
+
{
|
|
1616
|
+
id: "has-rationale",
|
|
1617
|
+
label: "Rationale provided",
|
|
1618
|
+
check: (ctx) => typeof ctx.data.rationale === "string" && ctx.data.rationale.length > 10,
|
|
1619
|
+
suggestion: () => "Add a rationale explaining why this rule exists via `update-entry`."
|
|
1620
|
+
},
|
|
1621
|
+
{
|
|
1622
|
+
id: "has-domain",
|
|
1623
|
+
label: "Domain specified",
|
|
1624
|
+
check: (ctx) => !!ctx.data.domain && ctx.data.domain !== "",
|
|
1625
|
+
suggestion: (ctx) => {
|
|
1626
|
+
const domain = inferDomain(`${ctx.name} ${ctx.description}`);
|
|
1627
|
+
return domain ? `Set domain \u2014 suggest: "${domain}" (inferred from content).` : "Specify the business domain this rule belongs to.";
|
|
1628
|
+
}
|
|
1629
|
+
}
|
|
1630
|
+
]
|
|
1631
|
+
}],
|
|
1632
|
+
["glossary", {
|
|
1633
|
+
idPrefix: "GT",
|
|
1634
|
+
governedDraft: true,
|
|
1635
|
+
descriptionField: "canonical",
|
|
1636
|
+
defaults: [
|
|
1637
|
+
{ key: "category", value: "infer" }
|
|
1638
|
+
],
|
|
1639
|
+
recommendedRelationTypes: ["defines_term_for", "confused_with", "related_to", "references"],
|
|
1640
|
+
inferField: (ctx) => {
|
|
1641
|
+
const fields = {};
|
|
1642
|
+
const area = inferArea(`${ctx.name} ${ctx.description}`);
|
|
1643
|
+
if (area) {
|
|
1644
|
+
const categoryMap = {
|
|
1645
|
+
"Architecture": "Platform & Architecture",
|
|
1646
|
+
"Knowledge Base": "Knowledge Management",
|
|
1647
|
+
"AI & MCP Integration": "AI & Developer Tools",
|
|
1648
|
+
"Developer Experience": "AI & Developer Tools",
|
|
1649
|
+
"Governance & Decision-Making": "Governance & Process",
|
|
1650
|
+
"Analytics & Tracking": "Platform & Architecture",
|
|
1651
|
+
"Security": "Platform & Architecture"
|
|
1652
|
+
};
|
|
1653
|
+
fields.category = categoryMap[area] ?? "";
|
|
1654
|
+
}
|
|
1655
|
+
return fields;
|
|
1656
|
+
},
|
|
1657
|
+
qualityChecks: [
|
|
1658
|
+
COMMON_CHECKS.clearName,
|
|
1659
|
+
{
|
|
1660
|
+
id: "has-canonical",
|
|
1661
|
+
label: "Canonical definition provided (>20 chars)",
|
|
1662
|
+
check: (ctx) => {
|
|
1663
|
+
const canonical = ctx.data.canonical;
|
|
1664
|
+
return typeof canonical === "string" && canonical.length > 20;
|
|
1665
|
+
},
|
|
1666
|
+
suggestion: () => "Add a clear canonical definition \u2014 this is the single source of truth for this term."
|
|
1667
|
+
},
|
|
1668
|
+
COMMON_CHECKS.hasRelations,
|
|
1669
|
+
{
|
|
1670
|
+
id: "has-category",
|
|
1671
|
+
label: "Category assigned",
|
|
1672
|
+
check: (ctx) => !!ctx.data.category && ctx.data.category !== "",
|
|
1673
|
+
suggestion: () => "Assign a category (e.g., 'Platform & Architecture', 'Governance & Process')."
|
|
1674
|
+
}
|
|
1675
|
+
]
|
|
1676
|
+
}],
|
|
1677
|
+
["decisions", {
|
|
1678
|
+
idPrefix: "DEC",
|
|
1679
|
+
governedDraft: false,
|
|
1680
|
+
descriptionField: "rationale",
|
|
1681
|
+
defaults: [
|
|
1682
|
+
{ key: "date", value: "today" },
|
|
1683
|
+
{ key: "decidedBy", value: "infer" }
|
|
1684
|
+
],
|
|
1685
|
+
recommendedRelationTypes: ["informs", "references", "replaces", "related_to"],
|
|
1686
|
+
inferField: (ctx) => {
|
|
1687
|
+
const fields = {};
|
|
1688
|
+
const area = inferArea(`${ctx.name} ${ctx.description}`);
|
|
1689
|
+
if (area) fields.decidedBy = area;
|
|
1690
|
+
return fields;
|
|
1691
|
+
},
|
|
1692
|
+
qualityChecks: [
|
|
1693
|
+
COMMON_CHECKS.clearName,
|
|
1694
|
+
{
|
|
1695
|
+
id: "has-rationale",
|
|
1696
|
+
label: "Rationale provided (>30 chars)",
|
|
1697
|
+
check: (ctx) => {
|
|
1698
|
+
const rationale = ctx.data.rationale;
|
|
1699
|
+
return typeof rationale === "string" && rationale.length > 30;
|
|
1700
|
+
},
|
|
1701
|
+
suggestion: () => "Explain why this decision was made \u2014 what was considered and rejected?"
|
|
1702
|
+
},
|
|
1703
|
+
COMMON_CHECKS.hasRelations,
|
|
1704
|
+
{
|
|
1705
|
+
id: "has-date",
|
|
1706
|
+
label: "Decision date recorded",
|
|
1707
|
+
check: (ctx) => !!ctx.data.date && ctx.data.date !== "",
|
|
1708
|
+
suggestion: () => "Record when this decision was made."
|
|
1709
|
+
}
|
|
1710
|
+
]
|
|
1711
|
+
}]
|
|
1712
|
+
]);
|
|
1713
|
+
var FALLBACK_PROFILE = {
|
|
1714
|
+
idPrefix: "",
|
|
1715
|
+
governedDraft: false,
|
|
1716
|
+
descriptionField: "description",
|
|
1717
|
+
defaults: [],
|
|
1718
|
+
recommendedRelationTypes: ["related_to", "references"],
|
|
1719
|
+
qualityChecks: [
|
|
1720
|
+
COMMON_CHECKS.clearName,
|
|
1721
|
+
COMMON_CHECKS.hasDescription,
|
|
1722
|
+
COMMON_CHECKS.hasRelations
|
|
1723
|
+
]
|
|
1724
|
+
};
|
|
1725
|
+
function generateEntryId(prefix) {
|
|
1726
|
+
if (!prefix) return "";
|
|
1727
|
+
const chars = "abcdefghijklmnopqrstuvwxyz0123456789";
|
|
1728
|
+
let suffix = "";
|
|
1729
|
+
for (let i = 0; i < 6; i++) {
|
|
1730
|
+
suffix += chars[Math.floor(Math.random() * chars.length)];
|
|
1731
|
+
}
|
|
1732
|
+
return `${prefix}-${suffix}`;
|
|
1733
|
+
}
|
|
1734
|
+
function extractSearchTerms(name, description) {
|
|
1735
|
+
const text = `${name} ${description}`;
|
|
1736
|
+
return text.replace(/[^\w\s]/g, " ").split(/\s+/).filter((w) => w.length > 3).slice(0, 8).join(" ");
|
|
1737
|
+
}
|
|
1738
|
+
function computeLinkConfidence(candidate, sourceName, sourceDescription, sourceCollection, candidateCollection) {
|
|
1739
|
+
const text = `${sourceName} ${sourceDescription}`.toLowerCase();
|
|
1740
|
+
const candidateName = candidate.name.toLowerCase();
|
|
1741
|
+
let score = 0;
|
|
1742
|
+
if (text.includes(candidateName) && candidateName.length > 3) {
|
|
1743
|
+
score += 40;
|
|
1744
|
+
}
|
|
1745
|
+
const candidateWords = candidateName.split(/\s+/).filter((w) => w.length > 3);
|
|
1746
|
+
const matchingWords = candidateWords.filter((w) => text.includes(w));
|
|
1747
|
+
score += matchingWords.length / Math.max(candidateWords.length, 1) * 30;
|
|
1748
|
+
const HUB_COLLECTIONS = /* @__PURE__ */ new Set(["strategy", "features"]);
|
|
1749
|
+
if (HUB_COLLECTIONS.has(candidateCollection)) {
|
|
1750
|
+
score += 15;
|
|
1751
|
+
}
|
|
1752
|
+
if (candidateCollection !== sourceCollection) {
|
|
1753
|
+
score += 10;
|
|
1754
|
+
}
|
|
1755
|
+
return Math.min(score, 100);
|
|
1756
|
+
}
|
|
1757
|
+
function inferRelationType(sourceCollection, targetCollection, profile) {
|
|
1758
|
+
const typeMap = {
|
|
1759
|
+
tensions: {
|
|
1760
|
+
glossary: "surfaces_tension_in",
|
|
1761
|
+
"business-rules": "references",
|
|
1762
|
+
strategy: "belongs_to",
|
|
1763
|
+
features: "surfaces_tension_in",
|
|
1764
|
+
decisions: "references"
|
|
1765
|
+
},
|
|
1766
|
+
"business-rules": {
|
|
1767
|
+
glossary: "references",
|
|
1768
|
+
features: "governs",
|
|
1769
|
+
strategy: "belongs_to",
|
|
1770
|
+
tensions: "references"
|
|
1771
|
+
},
|
|
1772
|
+
glossary: {
|
|
1773
|
+
features: "defines_term_for",
|
|
1774
|
+
"business-rules": "references",
|
|
1775
|
+
strategy: "references"
|
|
1776
|
+
},
|
|
1777
|
+
decisions: {
|
|
1778
|
+
features: "informs",
|
|
1779
|
+
"business-rules": "references",
|
|
1780
|
+
strategy: "references",
|
|
1781
|
+
tensions: "references"
|
|
1782
|
+
}
|
|
1783
|
+
};
|
|
1784
|
+
return typeMap[sourceCollection]?.[targetCollection] ?? profile.recommendedRelationTypes[0] ?? "related_to";
|
|
1785
|
+
}
|
|
1786
|
+
function scoreQuality(ctx, profile) {
|
|
1787
|
+
const checks = profile.qualityChecks.map((qc) => {
|
|
1788
|
+
const passed2 = qc.check(ctx);
|
|
1789
|
+
return {
|
|
1790
|
+
id: qc.id,
|
|
1791
|
+
label: qc.label,
|
|
1792
|
+
passed: passed2,
|
|
1793
|
+
suggestion: passed2 ? void 0 : qc.suggestion?.(ctx)
|
|
1794
|
+
};
|
|
1795
|
+
});
|
|
1796
|
+
const passed = checks.filter((c) => c.passed).length;
|
|
1797
|
+
const total = checks.length;
|
|
1798
|
+
const score = total > 0 ? Math.round(passed / total * 10) : 10;
|
|
1799
|
+
return { score, maxScore: 10, checks };
|
|
1800
|
+
}
|
|
1801
|
+
function formatQualityReport(result) {
|
|
1802
|
+
const lines = [`## Quality: ${result.score}/${result.maxScore}`];
|
|
1803
|
+
for (const check of result.checks) {
|
|
1804
|
+
const icon = check.passed ? "[x]" : "[ ]";
|
|
1805
|
+
const suggestion = check.passed ? "" : ` -- ${check.suggestion ?? ""}`;
|
|
1806
|
+
lines.push(`${icon} ${check.label}${suggestion}`);
|
|
1807
|
+
}
|
|
1808
|
+
return lines.join("\n");
|
|
1809
|
+
}
|
|
1810
|
+
async function checkEntryQuality(entryId) {
|
|
1811
|
+
const entry = await mcpQuery("kb.getEntry", { entryId });
|
|
1812
|
+
if (!entry) {
|
|
1813
|
+
return {
|
|
1814
|
+
text: `Entry \`${entryId}\` not found. Try kb-search to find the right ID.`,
|
|
1815
|
+
quality: { score: 0, maxScore: 10, checks: [] }
|
|
1816
|
+
};
|
|
1817
|
+
}
|
|
1818
|
+
const collections = await mcpQuery("kb.listCollections");
|
|
1819
|
+
const collMap = /* @__PURE__ */ new Map();
|
|
1820
|
+
for (const c of collections) collMap.set(c._id, c.slug);
|
|
1821
|
+
const collectionSlug = collMap.get(entry.collectionId) ?? "unknown";
|
|
1822
|
+
const profile = PROFILES.get(collectionSlug) ?? FALLBACK_PROFILE;
|
|
1823
|
+
const relations = await mcpQuery("kb.listEntryRelations", { entryId });
|
|
1824
|
+
const linksCreated = [];
|
|
1825
|
+
for (const r of relations) {
|
|
1826
|
+
const otherId = r.fromId === entry._id ? r.toId : r.fromId;
|
|
1827
|
+
linksCreated.push({
|
|
1828
|
+
targetEntryId: otherId,
|
|
1829
|
+
targetName: "",
|
|
1830
|
+
targetCollection: "",
|
|
1831
|
+
relationType: r.type
|
|
1832
|
+
});
|
|
1833
|
+
}
|
|
1834
|
+
const descField = profile.descriptionField;
|
|
1835
|
+
const description = typeof entry.data?.[descField] === "string" ? entry.data[descField] : "";
|
|
1836
|
+
const ctx = {
|
|
1837
|
+
collection: collectionSlug,
|
|
1838
|
+
name: entry.name,
|
|
1839
|
+
description,
|
|
1840
|
+
data: entry.data ?? {},
|
|
1841
|
+
entryId: entry.entryId ?? "",
|
|
1842
|
+
linksCreated,
|
|
1843
|
+
linksSuggested: [],
|
|
1844
|
+
collectionFields: []
|
|
1845
|
+
};
|
|
1846
|
+
const quality = scoreQuality(ctx, profile);
|
|
1847
|
+
const lines = [
|
|
1848
|
+
`# Quality Check: ${entry.entryId ?? entry.name}`,
|
|
1849
|
+
`**${entry.name}** in \`${collectionSlug}\` [${entry.status}]`,
|
|
1850
|
+
"",
|
|
1851
|
+
formatQualityReport(quality)
|
|
1852
|
+
];
|
|
1853
|
+
if (quality.score < 10) {
|
|
1854
|
+
const failedChecks = quality.checks.filter((c) => !c.passed && c.suggestion);
|
|
1855
|
+
if (failedChecks.length > 0) {
|
|
1856
|
+
lines.push("");
|
|
1857
|
+
lines.push(`_To improve: use \`update-entry\` to fill missing fields, or \`relate-entries\` to add connections._`);
|
|
1858
|
+
}
|
|
1859
|
+
}
|
|
1860
|
+
return { text: lines.join("\n"), quality };
|
|
1861
|
+
}
|
|
1862
|
+
var GOVERNED_COLLECTIONS = /* @__PURE__ */ new Set([
|
|
1863
|
+
"glossary",
|
|
1864
|
+
"business-rules",
|
|
1865
|
+
"principles",
|
|
1866
|
+
"standards",
|
|
1867
|
+
"strategy",
|
|
1868
|
+
"features"
|
|
1869
|
+
]);
|
|
1870
|
+
var AUTO_LINK_CONFIDENCE_THRESHOLD = 35;
|
|
1871
|
+
var MAX_AUTO_LINKS = 5;
|
|
1872
|
+
var MAX_SUGGESTIONS = 5;
|
|
1873
|
+
function registerSmartCaptureTools(server2) {
|
|
1874
|
+
server2.registerTool(
|
|
1875
|
+
"smart-capture",
|
|
1876
|
+
{
|
|
1877
|
+
title: "Smart Capture",
|
|
1878
|
+
description: "One-call knowledge capture: creates an entry, auto-links related entries, and returns a quality scorecard. Replaces the multi-step workflow of create-entry + suggest-links + relate-entries. Provide a collection, name, and description \u2014 everything else is inferred or auto-filled.\n\nSupported collections with smart profiles: tensions, business-rules, glossary, decisions.\nAll other collections use sensible defaults (same as quick-capture + auto-linking).\n\nAlways creates as 'draft' for governed collections. Embodies 'Capture Now, Curate Later' (PRI-81cbdq).",
|
|
1879
|
+
inputSchema: {
|
|
1880
|
+
collection: z5.string().describe("Collection slug, e.g. 'tensions', 'business-rules', 'glossary', 'decisions'"),
|
|
1881
|
+
name: z5.string().describe("Display name \u2014 be specific (e.g. 'Convex adjacency list won't scale for graph traversal')"),
|
|
1882
|
+
description: z5.string().describe("Full context \u2014 what's happening, why it matters, what you observed"),
|
|
1883
|
+
context: z5.string().optional().describe("Optional additional context (e.g. 'Observed during gather-context calls taking 700ms+')"),
|
|
1884
|
+
entryId: z5.string().optional().describe("Optional custom entry ID (e.g. 'TEN-my-id'). Auto-generated if omitted.")
|
|
1885
|
+
},
|
|
1886
|
+
annotations: { destructiveHint: false }
|
|
1887
|
+
},
|
|
1888
|
+
async ({ collection, name, description, context, entryId }) => {
|
|
1889
|
+
const profile = PROFILES.get(collection) ?? FALLBACK_PROFILE;
|
|
1890
|
+
const col = await mcpQuery("kb.getCollection", { slug: collection });
|
|
1891
|
+
if (!col) {
|
|
1892
|
+
return {
|
|
1893
|
+
content: [{ type: "text", text: `Collection \`${collection}\` not found. Use \`list-collections\` to see available collections.` }]
|
|
1894
|
+
};
|
|
1895
|
+
}
|
|
1896
|
+
const data = {};
|
|
1897
|
+
const today = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
|
|
1898
|
+
for (const field of col.fields ?? []) {
|
|
1899
|
+
const key = field.key;
|
|
1900
|
+
if (key === profile.descriptionField) {
|
|
1901
|
+
data[key] = description;
|
|
1902
|
+
} else if (field.type === "array" || field.type === "multi-select") {
|
|
1903
|
+
data[key] = [];
|
|
1904
|
+
} else {
|
|
1905
|
+
data[key] = "";
|
|
1906
|
+
}
|
|
1907
|
+
}
|
|
1908
|
+
for (const def of profile.defaults) {
|
|
1909
|
+
if (def.value === "today") {
|
|
1910
|
+
data[def.key] = today;
|
|
1911
|
+
} else if (def.value !== "infer") {
|
|
1912
|
+
data[def.key] = def.value;
|
|
1913
|
+
}
|
|
1914
|
+
}
|
|
1915
|
+
if (profile.inferField) {
|
|
1916
|
+
const inferred = profile.inferField({
|
|
1917
|
+
collection,
|
|
1918
|
+
name,
|
|
1919
|
+
description,
|
|
1920
|
+
context,
|
|
1921
|
+
data,
|
|
1922
|
+
entryId: "",
|
|
1923
|
+
linksCreated: [],
|
|
1924
|
+
linksSuggested: [],
|
|
1925
|
+
collectionFields: col.fields ?? []
|
|
1926
|
+
});
|
|
1927
|
+
for (const [key, val] of Object.entries(inferred)) {
|
|
1928
|
+
if (val !== void 0 && val !== "") {
|
|
1929
|
+
data[key] = val;
|
|
1930
|
+
}
|
|
1931
|
+
}
|
|
1932
|
+
}
|
|
1933
|
+
if (!data[profile.descriptionField] && !data.description && !data.canonical) {
|
|
1934
|
+
data[profile.descriptionField || "description"] = description;
|
|
1935
|
+
}
|
|
1936
|
+
const status = GOVERNED_COLLECTIONS.has(collection) ? "draft" : "draft";
|
|
1937
|
+
const finalEntryId = entryId ?? generateEntryId(profile.idPrefix);
|
|
1938
|
+
let internalId;
|
|
1939
|
+
try {
|
|
1940
|
+
internalId = await mcpMutation("kb.createEntry", {
|
|
1941
|
+
collectionSlug: collection,
|
|
1942
|
+
entryId: finalEntryId || void 0,
|
|
1943
|
+
name,
|
|
1944
|
+
status,
|
|
1945
|
+
data,
|
|
1946
|
+
createdBy: "smart-capture"
|
|
1947
|
+
});
|
|
1948
|
+
} catch (error) {
|
|
1949
|
+
const msg = error instanceof Error ? error.message : String(error);
|
|
1950
|
+
if (msg.includes("Duplicate") || msg.includes("already exists")) {
|
|
1951
|
+
return {
|
|
1952
|
+
content: [{
|
|
1953
|
+
type: "text",
|
|
1954
|
+
text: `# Cannot Capture \u2014 Duplicate Detected
|
|
1955
|
+
|
|
1956
|
+
${msg}
|
|
1957
|
+
|
|
1958
|
+
Use \`get-entry\` to inspect the existing entry, or \`update-entry\` to modify it.`
|
|
1959
|
+
}]
|
|
1960
|
+
};
|
|
1961
|
+
}
|
|
1962
|
+
throw error;
|
|
1963
|
+
}
|
|
1964
|
+
const linksCreated = [];
|
|
1965
|
+
const linksSuggested = [];
|
|
1966
|
+
const searchQuery = extractSearchTerms(name, description);
|
|
1967
|
+
if (searchQuery) {
|
|
1968
|
+
const [searchResults, allCollections] = await Promise.all([
|
|
1969
|
+
mcpQuery("kb.searchEntries", { query: searchQuery }),
|
|
1970
|
+
mcpQuery("kb.listCollections")
|
|
1971
|
+
]);
|
|
1972
|
+
const collMap = /* @__PURE__ */ new Map();
|
|
1973
|
+
for (const c of allCollections) collMap.set(c._id, c.slug);
|
|
1974
|
+
const candidates = (searchResults ?? []).filter((r) => r.entryId !== finalEntryId && r._id !== internalId).map((r) => ({
|
|
1975
|
+
...r,
|
|
1976
|
+
collSlug: collMap.get(r.collectionId) ?? "unknown",
|
|
1977
|
+
confidence: computeLinkConfidence(r, name, description, collection, collMap.get(r.collectionId) ?? "unknown")
|
|
1978
|
+
})).sort((a, b) => b.confidence - a.confidence);
|
|
1979
|
+
for (const c of candidates) {
|
|
1980
|
+
if (linksCreated.length >= MAX_AUTO_LINKS) break;
|
|
1981
|
+
if (c.confidence < AUTO_LINK_CONFIDENCE_THRESHOLD) break;
|
|
1982
|
+
if (!c.entryId || !finalEntryId) continue;
|
|
1983
|
+
const relationType = inferRelationType(collection, c.collSlug, profile);
|
|
1984
|
+
try {
|
|
1985
|
+
await mcpMutation("kb.createEntryRelation", {
|
|
1986
|
+
fromEntryId: finalEntryId,
|
|
1987
|
+
toEntryId: c.entryId,
|
|
1988
|
+
type: relationType
|
|
1989
|
+
});
|
|
1990
|
+
linksCreated.push({
|
|
1991
|
+
targetEntryId: c.entryId,
|
|
1992
|
+
targetName: c.name,
|
|
1993
|
+
targetCollection: c.collSlug,
|
|
1994
|
+
relationType
|
|
1995
|
+
});
|
|
1996
|
+
} catch {
|
|
1997
|
+
}
|
|
1998
|
+
}
|
|
1999
|
+
const linkedIds = new Set(linksCreated.map((l) => l.targetEntryId));
|
|
2000
|
+
for (const c of candidates) {
|
|
2001
|
+
if (linksSuggested.length >= MAX_SUGGESTIONS) break;
|
|
2002
|
+
if (linkedIds.has(c.entryId)) continue;
|
|
2003
|
+
if (c.confidence < 10) continue;
|
|
2004
|
+
const preview = extractPreview2(c.data, 80);
|
|
2005
|
+
const reason = c.confidence >= AUTO_LINK_CONFIDENCE_THRESHOLD ? "high relevance (already linked)" : `"${c.name.toLowerCase().split(/\s+/).filter((w) => `${name} ${description}`.toLowerCase().includes(w) && w.length > 3).slice(0, 2).join('", "')}" appears in content`;
|
|
2006
|
+
linksSuggested.push({
|
|
2007
|
+
entryId: c.entryId,
|
|
2008
|
+
name: c.name,
|
|
2009
|
+
collection: c.collSlug,
|
|
2010
|
+
reason,
|
|
2011
|
+
preview
|
|
2012
|
+
});
|
|
2013
|
+
}
|
|
2014
|
+
}
|
|
2015
|
+
const captureCtx = {
|
|
2016
|
+
collection,
|
|
2017
|
+
name,
|
|
2018
|
+
description,
|
|
2019
|
+
context,
|
|
2020
|
+
data,
|
|
2021
|
+
entryId: finalEntryId,
|
|
2022
|
+
linksCreated,
|
|
2023
|
+
linksSuggested,
|
|
2024
|
+
collectionFields: col.fields ?? []
|
|
2025
|
+
};
|
|
2026
|
+
const quality = scoreQuality(captureCtx, profile);
|
|
2027
|
+
const lines = [
|
|
2028
|
+
`# Captured: ${finalEntryId || name}`,
|
|
2029
|
+
`**${name}** added to \`${collection}\` as \`${status}\``
|
|
2030
|
+
];
|
|
2031
|
+
if (linksCreated.length > 0) {
|
|
2032
|
+
lines.push("");
|
|
2033
|
+
lines.push(`## Auto-linked (${linksCreated.length})`);
|
|
2034
|
+
for (const link of linksCreated) {
|
|
2035
|
+
lines.push(`- -> **${link.relationType}** ${link.targetEntryId}: ${link.targetName} [${link.targetCollection}]`);
|
|
2036
|
+
}
|
|
2037
|
+
}
|
|
2038
|
+
if (linksSuggested.length > 0) {
|
|
2039
|
+
lines.push("");
|
|
2040
|
+
lines.push("## Suggested links (review and use relate-entries)");
|
|
2041
|
+
for (let i = 0; i < linksSuggested.length; i++) {
|
|
2042
|
+
const s = linksSuggested[i];
|
|
2043
|
+
const preview = s.preview ? ` \u2014 ${s.preview}` : "";
|
|
2044
|
+
lines.push(`${i + 1}. **${s.entryId ?? "(no ID)"}**: ${s.name} [${s.collection}]${preview}`);
|
|
2045
|
+
}
|
|
2046
|
+
}
|
|
2047
|
+
lines.push("");
|
|
2048
|
+
lines.push(formatQualityReport(quality));
|
|
2049
|
+
const failedChecks = quality.checks.filter((c) => !c.passed);
|
|
2050
|
+
if (failedChecks.length > 0) {
|
|
2051
|
+
lines.push("");
|
|
2052
|
+
lines.push(`_To improve: \`update-entry entryId="${finalEntryId}"\` to fill missing fields._`);
|
|
2053
|
+
}
|
|
2054
|
+
return { content: [{ type: "text", text: lines.join("\n") }] };
|
|
2055
|
+
}
|
|
2056
|
+
);
|
|
2057
|
+
server2.registerTool(
|
|
2058
|
+
"quality-check",
|
|
2059
|
+
{
|
|
2060
|
+
title: "Quality Check",
|
|
2061
|
+
description: "Score an existing knowledge entry against collection-specific quality criteria. Returns a scorecard (X/10) with specific, actionable suggestions for improvement. Checks: name clarity, description completeness, relation connectedness, and collection-specific fields.\n\nUse after creating entries to assess their quality, or to audit existing entries.",
|
|
2062
|
+
inputSchema: {
|
|
2063
|
+
entryId: z5.string().describe("Entry ID to check, e.g. 'TEN-graph-db', 'GT-019', 'SOS-006'")
|
|
2064
|
+
},
|
|
2065
|
+
annotations: { readOnlyHint: true }
|
|
2066
|
+
},
|
|
2067
|
+
async ({ entryId }) => {
|
|
2068
|
+
const result = await checkEntryQuality(entryId);
|
|
2069
|
+
return { content: [{ type: "text", text: result.text }] };
|
|
2070
|
+
}
|
|
2071
|
+
);
|
|
2072
|
+
}
|
|
2073
|
+
function extractPreview2(data, maxLen) {
|
|
2074
|
+
if (!data || typeof data !== "object") return "";
|
|
2075
|
+
const raw = data.description ?? data.canonical ?? data.detail ?? data.rule ?? "";
|
|
2076
|
+
if (typeof raw !== "string" || !raw) return "";
|
|
2077
|
+
return raw.length > maxLen ? raw.substring(0, maxLen) + "..." : raw;
|
|
2078
|
+
}
|
|
2079
|
+
|
|
2080
|
+
// src/resources/index.ts
|
|
2081
|
+
import { ResourceTemplate } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
2082
|
+
function formatEntryMarkdown(entry) {
|
|
2083
|
+
const id = entry.entryId ? `${entry.entryId}: ` : "";
|
|
2084
|
+
const lines = [`## ${id}${entry.name} [${entry.status}]`];
|
|
2085
|
+
if (entry.data && typeof entry.data === "object") {
|
|
2086
|
+
for (const [key, val] of Object.entries(entry.data)) {
|
|
2087
|
+
if (val && key !== "rawData") {
|
|
2088
|
+
lines.push(`**${key}**: ${typeof val === "string" ? val : JSON.stringify(val)}`);
|
|
2089
|
+
}
|
|
2090
|
+
}
|
|
2091
|
+
}
|
|
2092
|
+
return lines.join("\n");
|
|
2093
|
+
}
|
|
2094
|
+
function buildOrientationMarkdown(collections, trackingEvents, standards, businessRules) {
|
|
2095
|
+
const sections = ["# ProductBrain \u2014 Orientation"];
|
|
2096
|
+
sections.push(
|
|
2097
|
+
"## Architecture\n```\nCursor (stdio) \u2192 MCP Server (mcp-server/src/index.ts)\n \u2192 POST /api/mcp with Bearer token\n \u2192 Convex HTTP Action (convex/http.ts)\n \u2192 internalQuery / internalMutation (convex/mcpKnowledge.ts)\n \u2192 Convex DB (workspace-scoped)\n```\nSecurity: API key auth on every request, workspace-scoped data, internal functions blocked from external clients.\nKey files: `mcp-server/src/client.ts` (HTTP client + audit), `convex/schema.ts` (9-table schema)."
|
|
2098
|
+
);
|
|
2099
|
+
if (collections) {
|
|
2100
|
+
const collList = collections.map((c) => {
|
|
2101
|
+
const prefix = c.icon ? `${c.icon} ` : "";
|
|
2102
|
+
return `- ${prefix}**${c.name}** (\`${c.slug}\`) \u2014 ${c.description || "no description"}`;
|
|
2103
|
+
}).join("\n");
|
|
2104
|
+
sections.push(
|
|
2105
|
+
`## Data Model (${collections.length} collections)
|
|
2106
|
+
Unified entries model: collections define field schemas, entries hold data in a flexible \`data\` field.
|
|
2107
|
+
Tags for filtering (e.g. \`severity:high\`), relations via \`entryRelations\`, history via \`entryHistory\`, labels via \`labels\` + \`entryLabels\`.
|
|
2108
|
+
|
|
2109
|
+
` + collList + "\n\nUse `list-collections` for field schemas, `get-entry` for full records."
|
|
2110
|
+
);
|
|
2111
|
+
} else {
|
|
2112
|
+
sections.push(
|
|
2113
|
+
"## Data Model\nCould not load collections \u2014 use `list-collections` to browse manually."
|
|
2114
|
+
);
|
|
2115
|
+
}
|
|
2116
|
+
const rulesCount = businessRules ? `${businessRules.length} entries` : "not loaded \u2014 collection may not exist yet";
|
|
2117
|
+
sections.push(
|
|
2118
|
+
`## Business Rules
|
|
2119
|
+
Collection: \`business-rules\` (${rulesCount}).
|
|
2120
|
+
Find rules: \`kb-search\` for text search, \`list-entries collection=business-rules\` to browse.
|
|
2121
|
+
Check compliance: use the \`review-against-rules\` prompt (pass a domain).
|
|
2122
|
+
Draft a new rule: use the \`draft-rule-from-context\` prompt.`
|
|
2123
|
+
);
|
|
2124
|
+
const eventsCount = trackingEvents ? `${trackingEvents.length} events` : "not loaded \u2014 collection may not exist yet";
|
|
2125
|
+
const conventionNote = standards ? "Naming convention: `object_action` in snake_case with past-tense verbs (from standards collection)." : "Naming convention: `object_action` in snake_case with past-tense verbs.";
|
|
2126
|
+
sections.push(
|
|
2127
|
+
`## Analytics & Tracking
|
|
2128
|
+
Event catalog: \`tracking-events\` collection (${eventsCount}).
|
|
2129
|
+
${conventionNote}
|
|
2130
|
+
Implementation: \`src/lib/analytics.ts\`. Workspace-scoped events MUST use \`withWorkspaceGroup()\`.
|
|
2131
|
+
Browse: \`list-entries collection=tracking-events\`. Full setup: \`docs/posthog-setup.md\`.`
|
|
2132
|
+
);
|
|
2133
|
+
sections.push(
|
|
2134
|
+
"## Knowledge Graph\nEntries are connected via typed relations (`entryRelations` table). Relations are bidirectional and collection-agnostic \u2014 any entry can link to any other entry.\n\n**Recommended relation types** (extensible \u2014 any string accepted):\n- `governs` \u2014 a rule constrains behavior of a feature\n- `defines_term_for` \u2014 a glossary term is canonical vocabulary for a feature/area\n- `belongs_to` \u2014 a feature belongs to a product area or parent concept\n- `informs` \u2014 a decision or insight informs a feature\n- `surfaces_tension_in` \u2014 a tension exists within a feature area\n- `related_to`, `depends_on`, `replaces`, `conflicts_with`, `references`, `confused_with`\n\nEach relation type is defined as a glossary entry (prefix `GT-REL-*`) to prevent terminology drift.\n\n**Tools:**\n- `gather-context` \u2014 get the full context around any entry (multi-hop graph traversal)\n- `suggest-links` \u2014 discover potential connections for an entry\n- `relate-entries` \u2014 create a typed link between two entries\n- `find-related` \u2014 list direct relations for an entry\n\n**Convention:** When creating or updating entries in governed collections, always use `suggest-links` to discover and create relevant relations."
|
|
2135
|
+
);
|
|
2136
|
+
sections.push(
|
|
2137
|
+
"## Creating Knowledge\nUse `smart-capture` as the primary tool for creating new entries. It handles the full workflow in one call:\n1. Creates the entry with collection-aware defaults (auto-fills dates, infers domains, sets priority)\n2. Auto-links related entries from across the knowledge base (up to 5 confident matches)\n3. Returns a quality scorecard (X/10) with actionable improvement suggestions\n\n**Smart profiles** exist for: `tensions`, `business-rules`, `glossary`, `decisions`.\nAll other collections use sensible defaults.\n\nExample: `smart-capture collection='tensions' name='...' description='...'`\n\nUse `quality-check` to score existing entries retroactively.\nUse `create-entry` only when you need full control over every field.\nUse `quick-capture` for minimal ceremony without auto-linking."
|
|
2138
|
+
);
|
|
2139
|
+
sections.push(
|
|
2140
|
+
"## Where to Go Next\n- **Create entry** \u2192 `smart-capture` tool (auto-links + quality score in one call)\n- **Full context** \u2192 `gather-context` tool (start here when working on a feature)\n- **Discover links** \u2192 `suggest-links` tool\n- **Quality audit** \u2192 `quality-check` tool\n- **Terminology** \u2192 `name-check` prompt or `productbrain://terminology` resource\n- **Schema details** \u2192 `productbrain://collections` resource or `list-collections` tool\n- **Labels** \u2192 `productbrain://labels` resource or `list-labels` tool\n- **Any collection** \u2192 `productbrain://{slug}/entries` resource\n- **Log a decision** \u2192 `draft-decision-record` prompt\n- **Health check** \u2192 `health` tool\n- **Debug MCP calls** \u2192 `mcp-audit` tool"
|
|
2141
|
+
);
|
|
2142
|
+
return sections.join("\n\n---\n\n");
|
|
2143
|
+
}
|
|
2144
|
+
function registerResources(server2) {
|
|
2145
|
+
server2.resource(
|
|
2146
|
+
"kb-orientation",
|
|
2147
|
+
"productbrain://orientation",
|
|
2148
|
+
async (uri) => {
|
|
2149
|
+
const [collectionsResult, eventsResult, standardsResult, rulesResult] = await Promise.allSettled([
|
|
2150
|
+
mcpQuery("kb.listCollections"),
|
|
2151
|
+
mcpQuery("kb.listEntries", { collectionSlug: "tracking-events" }),
|
|
2152
|
+
mcpQuery("kb.listEntries", { collectionSlug: "standards" }),
|
|
2153
|
+
mcpQuery("kb.listEntries", { collectionSlug: "business-rules" })
|
|
2154
|
+
]);
|
|
2155
|
+
const collections = collectionsResult.status === "fulfilled" ? collectionsResult.value : null;
|
|
2156
|
+
const trackingEvents = eventsResult.status === "fulfilled" ? eventsResult.value : null;
|
|
2157
|
+
const standards = standardsResult.status === "fulfilled" ? standardsResult.value : null;
|
|
2158
|
+
const businessRules = rulesResult.status === "fulfilled" ? rulesResult.value : null;
|
|
2159
|
+
return {
|
|
2160
|
+
contents: [{
|
|
2161
|
+
uri: uri.href,
|
|
2162
|
+
text: buildOrientationMarkdown(collections, trackingEvents, standards, businessRules),
|
|
2163
|
+
mimeType: "text/markdown"
|
|
2164
|
+
}]
|
|
2165
|
+
};
|
|
2166
|
+
}
|
|
2167
|
+
);
|
|
2168
|
+
server2.resource(
|
|
2169
|
+
"kb-terminology",
|
|
2170
|
+
"productbrain://terminology",
|
|
2171
|
+
async (uri) => {
|
|
2172
|
+
const [glossaryResult, standardsResult] = await Promise.allSettled([
|
|
2173
|
+
mcpQuery("kb.listEntries", { collectionSlug: "glossary" }),
|
|
2174
|
+
mcpQuery("kb.listEntries", { collectionSlug: "standards" })
|
|
2175
|
+
]);
|
|
2176
|
+
const lines = ["# ProductBrain \u2014 Terminology"];
|
|
2177
|
+
if (glossaryResult.status === "fulfilled") {
|
|
2178
|
+
if (glossaryResult.value.length > 0) {
|
|
2179
|
+
const terms = glossaryResult.value.map((t) => `- **${t.name}** (${t.entryId ?? "\u2014"}) [${t.status}]: ${t.data?.canonical ?? t.data?.description ?? ""}`).join("\n");
|
|
2180
|
+
lines.push(`## Glossary (${glossaryResult.value.length} terms)
|
|
2181
|
+
|
|
2182
|
+
${terms}`);
|
|
2183
|
+
} else {
|
|
2184
|
+
lines.push("## Glossary\n\nNo glossary terms yet. Use `create-entry` with collection `glossary` to add terms.");
|
|
2185
|
+
}
|
|
2186
|
+
} else {
|
|
2187
|
+
lines.push("## Glossary\n\nCould not load glossary \u2014 use `list-entries collection=glossary` to browse manually.");
|
|
2188
|
+
}
|
|
2189
|
+
if (standardsResult.status === "fulfilled") {
|
|
2190
|
+
if (standardsResult.value.length > 0) {
|
|
2191
|
+
const stds = standardsResult.value.map((s) => `- **${s.name}** (${s.entryId ?? "\u2014"}) [${s.status}]: ${s.data?.description ?? ""}`).join("\n");
|
|
2192
|
+
lines.push(`## Standards (${standardsResult.value.length} entries)
|
|
2193
|
+
|
|
2194
|
+
${stds}`);
|
|
2195
|
+
} else {
|
|
2196
|
+
lines.push("## Standards\n\nNo standards yet. Use `create-entry` with collection `standards` to add standards.");
|
|
2197
|
+
}
|
|
2198
|
+
} else {
|
|
2199
|
+
lines.push("## Standards\n\nCould not load standards \u2014 use `list-entries collection=standards` to browse manually.");
|
|
2200
|
+
}
|
|
2201
|
+
return {
|
|
2202
|
+
contents: [{ uri: uri.href, text: lines.join("\n\n---\n\n"), mimeType: "text/markdown" }]
|
|
2203
|
+
};
|
|
2204
|
+
}
|
|
2205
|
+
);
|
|
2206
|
+
server2.resource(
|
|
2207
|
+
"kb-collections",
|
|
2208
|
+
"productbrain://collections",
|
|
2209
|
+
async (uri) => {
|
|
2210
|
+
const collections = await mcpQuery("kb.listCollections");
|
|
2211
|
+
if (collections.length === 0) {
|
|
2212
|
+
return { contents: [{ uri: uri.href, text: "No collections in this workspace.", mimeType: "text/markdown" }] };
|
|
2213
|
+
}
|
|
2214
|
+
const formatted = collections.map((c) => {
|
|
2215
|
+
const fieldList = c.fields.map((f) => ` - \`${f.key}\` (${f.type}${f.required ? ", required" : ""}${f.searchable ? ", searchable" : ""})`).join("\n");
|
|
2216
|
+
return `## ${c.icon ?? ""} ${c.name} (\`${c.slug}\`)
|
|
2217
|
+
${c.description || ""}
|
|
2218
|
+
|
|
2219
|
+
**Fields:**
|
|
2220
|
+
${fieldList}`;
|
|
2221
|
+
}).join("\n\n---\n\n");
|
|
2222
|
+
return {
|
|
2223
|
+
contents: [{ uri: uri.href, text: `# Knowledge Collections (${collections.length})
|
|
2224
|
+
|
|
2225
|
+
${formatted}`, mimeType: "text/markdown" }]
|
|
2226
|
+
};
|
|
2227
|
+
}
|
|
2228
|
+
);
|
|
2229
|
+
server2.resource(
|
|
2230
|
+
"kb-collection-entries",
|
|
2231
|
+
new ResourceTemplate("productbrain://{slug}/entries", {
|
|
2232
|
+
list: async () => {
|
|
2233
|
+
const collections = await mcpQuery("kb.listCollections");
|
|
2234
|
+
return {
|
|
2235
|
+
resources: collections.map((c) => ({
|
|
2236
|
+
uri: `productbrain://${c.slug}/entries`,
|
|
2237
|
+
name: `${c.icon ?? ""} ${c.name}`.trim()
|
|
2238
|
+
}))
|
|
2239
|
+
};
|
|
2240
|
+
}
|
|
2241
|
+
}),
|
|
2242
|
+
async (uri, { slug }) => {
|
|
2243
|
+
const entries = await mcpQuery("kb.listEntries", { collectionSlug: slug });
|
|
2244
|
+
const formatted = entries.map(formatEntryMarkdown).join("\n\n---\n\n");
|
|
2245
|
+
return {
|
|
2246
|
+
contents: [{
|
|
2247
|
+
uri: uri.href,
|
|
2248
|
+
text: formatted || "No entries in this collection.",
|
|
2249
|
+
mimeType: "text/markdown"
|
|
2250
|
+
}]
|
|
2251
|
+
};
|
|
2252
|
+
}
|
|
2253
|
+
);
|
|
2254
|
+
server2.resource(
|
|
2255
|
+
"kb-labels",
|
|
2256
|
+
"productbrain://labels",
|
|
2257
|
+
async (uri) => {
|
|
2258
|
+
const labels = await mcpQuery("kb.listLabels");
|
|
2259
|
+
if (labels.length === 0) {
|
|
2260
|
+
return { contents: [{ uri: uri.href, text: "No labels in this workspace.", mimeType: "text/markdown" }] };
|
|
2261
|
+
}
|
|
2262
|
+
const groups = labels.filter((l) => l.isGroup);
|
|
2263
|
+
const ungrouped = labels.filter((l) => !l.isGroup && !l.parentId);
|
|
2264
|
+
const children = (parentId) => labels.filter((l) => l.parentId === parentId);
|
|
2265
|
+
const lines = [];
|
|
2266
|
+
for (const group of groups) {
|
|
2267
|
+
lines.push(`## ${group.name}`);
|
|
2268
|
+
for (const child of children(group._id)) {
|
|
2269
|
+
lines.push(`- \`${child.slug}\` ${child.name}${child.color ? ` (${child.color})` : ""}`);
|
|
2270
|
+
}
|
|
2271
|
+
}
|
|
2272
|
+
if (ungrouped.length > 0) {
|
|
2273
|
+
lines.push("## Ungrouped");
|
|
2274
|
+
for (const l of ungrouped) {
|
|
2275
|
+
lines.push(`- \`${l.slug}\` ${l.name}${l.color ? ` (${l.color})` : ""}`);
|
|
2276
|
+
}
|
|
2277
|
+
}
|
|
2278
|
+
return {
|
|
2279
|
+
contents: [{ uri: uri.href, text: `# Workspace Labels (${labels.length})
|
|
2280
|
+
|
|
2281
|
+
${lines.join("\n")}`, mimeType: "text/markdown" }]
|
|
2282
|
+
};
|
|
2283
|
+
}
|
|
2284
|
+
);
|
|
2285
|
+
}
|
|
2286
|
+
|
|
2287
|
+
// src/prompts/index.ts
|
|
2288
|
+
import { z as z6 } from "zod";
|
|
2289
|
+
function registerPrompts(server2) {
|
|
2290
|
+
server2.prompt(
|
|
2291
|
+
"review-against-rules",
|
|
2292
|
+
"Review code or a design decision against all business rules for a given domain. Fetches the rules and asks you to do a structured compliance review.",
|
|
2293
|
+
{ domain: z6.string().describe("Business rule domain (e.g. 'Identity & Access', 'Governance & Decision-Making')") },
|
|
2294
|
+
async ({ domain }) => {
|
|
2295
|
+
const entries = await mcpQuery("kb.listEntries", { collectionSlug: "business-rules" });
|
|
2296
|
+
const rules = entries.filter((e) => e.data?.domain === domain);
|
|
2297
|
+
if (rules.length === 0) {
|
|
2298
|
+
return {
|
|
2299
|
+
messages: [
|
|
2300
|
+
{
|
|
2301
|
+
role: "user",
|
|
2302
|
+
content: {
|
|
2303
|
+
type: "text",
|
|
2304
|
+
text: `No business rules found for domain "${domain}". Use the list-entries tool with collection "business-rules" to see available domains.`
|
|
2305
|
+
}
|
|
2306
|
+
}
|
|
2307
|
+
]
|
|
2308
|
+
};
|
|
2309
|
+
}
|
|
2310
|
+
const rulesText = rules.map(
|
|
2311
|
+
(r) => `### ${r.entryId ?? ""}: ${r.name}
|
|
2312
|
+
Status: ${r.status} | Severity: ${r.data?.severity ?? "unknown"}
|
|
2313
|
+
Description: ${r.data?.description ?? ""}
|
|
2314
|
+
Data Impact: ${r.data?.dataImpact ?? ""}
|
|
2315
|
+
Platforms: ${(r.data?.platforms ?? []).join(", ")}
|
|
2316
|
+
` + (r.data?.conflictWith ? `CONFLICT: ${r.data.conflictWith.rule} \u2014 ${r.data.conflictWith.nature}
|
|
2317
|
+
` : "")
|
|
2318
|
+
).join("\n---\n\n");
|
|
2319
|
+
return {
|
|
2320
|
+
messages: [
|
|
2321
|
+
{
|
|
2322
|
+
role: "user",
|
|
2323
|
+
content: {
|
|
2324
|
+
type: "text",
|
|
2325
|
+
text: `Review the current code or design against the following business rules for the "${domain}" domain.
|
|
2326
|
+
|
|
2327
|
+
For each rule, assess:
|
|
2328
|
+
1. Is the current implementation compliant?
|
|
2329
|
+
2. Are there potential violations or edge cases?
|
|
2330
|
+
3. What specific changes would be needed for compliance?
|
|
2331
|
+
|
|
2332
|
+
Business Rules:
|
|
2333
|
+
|
|
2334
|
+
${rulesText}
|
|
2335
|
+
|
|
2336
|
+
Provide a structured review with a compliance status for each rule (COMPLIANT / AT RISK / VIOLATION / NOT APPLICABLE).`
|
|
2337
|
+
}
|
|
2338
|
+
}
|
|
2339
|
+
]
|
|
2340
|
+
};
|
|
2341
|
+
}
|
|
2342
|
+
);
|
|
2343
|
+
server2.prompt(
|
|
2344
|
+
"name-check",
|
|
2345
|
+
"Check variable names, field names, or API names against the glossary for terminology alignment. Flags drift from canonical terms.",
|
|
2346
|
+
{ names: z6.string().describe("Comma-separated list of names to check (e.g. 'vendor_id, compliance_level, formulator_type')") },
|
|
2347
|
+
async ({ names }) => {
|
|
2348
|
+
const terms = await mcpQuery("kb.listEntries", { collectionSlug: "glossary" });
|
|
2349
|
+
const glossaryContext = terms.map(
|
|
2350
|
+
(t) => `${t.name} (${t.entryId ?? ""}) [${t.status}]: ${t.data?.canonical ?? ""}` + (t.data?.confusedWith?.length > 0 ? ` \u2014 Often confused with: ${t.data.confusedWith.join(", ")}` : "") + (t.data?.codeMapping?.length > 0 ? `
|
|
2351
|
+
Code mappings: ${t.data.codeMapping.map((m) => `${m.platform}:${m.field}`).join(", ")}` : "")
|
|
2352
|
+
).join("\n");
|
|
2353
|
+
return {
|
|
2354
|
+
messages: [
|
|
2355
|
+
{
|
|
2356
|
+
role: "user",
|
|
2357
|
+
content: {
|
|
2358
|
+
type: "text",
|
|
2359
|
+
text: `Check the following names against the glossary for terminology alignment:
|
|
2360
|
+
|
|
2361
|
+
Names to check: ${names}
|
|
2362
|
+
|
|
2363
|
+
Glossary (canonical terms):
|
|
2364
|
+
${glossaryContext}
|
|
2365
|
+
|
|
2366
|
+
For each name:
|
|
2367
|
+
1. Does it match a canonical term? If so, which one?
|
|
2368
|
+
2. Is there terminology drift? (e.g. using "vendor" instead of "supplier", "compliance" instead of "conformance")
|
|
2369
|
+
3. Suggest the canonical alternative if drift is detected.
|
|
2370
|
+
4. Flag any names that don't have a corresponding glossary term (might need one).
|
|
2371
|
+
|
|
2372
|
+
Format as a table: Name | Status | Canonical Form | Action Needed`
|
|
2373
|
+
}
|
|
2374
|
+
}
|
|
2375
|
+
]
|
|
2376
|
+
};
|
|
2377
|
+
}
|
|
2378
|
+
);
|
|
2379
|
+
server2.prompt(
|
|
2380
|
+
"draft-decision-record",
|
|
2381
|
+
"Draft a structured decision record from a description of what was decided. Includes context from recent decisions and relevant rules.",
|
|
2382
|
+
{ context: z6.string().describe("Description of the decision (e.g. 'We decided to use MRSL v3.1 as the conformance baseline because...')") },
|
|
2383
|
+
async ({ context }) => {
|
|
2384
|
+
const recentDecisions = await mcpQuery("kb.listEntries", { collectionSlug: "decisions" });
|
|
2385
|
+
const sorted = [...recentDecisions].sort((a, b) => (b.data?.date ?? "") > (a.data?.date ?? "") ? 1 : -1).slice(0, 5);
|
|
2386
|
+
const recentContext = sorted.length > 0 ? sorted.map((d) => `- [${d.status}] ${d.name} (${d.data?.date ?? "no date"})`).join("\n") : "No previous decisions recorded.";
|
|
2387
|
+
return {
|
|
2388
|
+
messages: [
|
|
2389
|
+
{
|
|
2390
|
+
role: "user",
|
|
2391
|
+
content: {
|
|
2392
|
+
type: "text",
|
|
2393
|
+
text: `Draft a structured decision record from the following context:
|
|
2394
|
+
|
|
2395
|
+
"${context}"
|
|
2396
|
+
|
|
2397
|
+
Recent decisions for reference:
|
|
2398
|
+
${recentContext}
|
|
2399
|
+
|
|
2400
|
+
Structure the decision record with:
|
|
2401
|
+
1. **Title**: Concise decision statement
|
|
2402
|
+
2. **Decided by**: Who made or approved this decision
|
|
2403
|
+
3. **Date**: When it was decided
|
|
2404
|
+
4. **Status**: decided / proposed / revisited
|
|
2405
|
+
5. **Rationale**: Why this decision was made, including trade-offs considered
|
|
2406
|
+
6. **Alternatives considered**: What else was on the table
|
|
2407
|
+
7. **Related rules or tensions**: Any business rules or tensions this connects to
|
|
2408
|
+
|
|
2409
|
+
After drafting, I can log it using the create-entry tool with collection "decisions".`
|
|
2410
|
+
}
|
|
2411
|
+
}
|
|
2412
|
+
]
|
|
2413
|
+
};
|
|
2414
|
+
}
|
|
2415
|
+
);
|
|
2416
|
+
server2.prompt(
|
|
2417
|
+
"draft-rule-from-context",
|
|
2418
|
+
"Draft a new business rule from an observation or discovery made while coding. Fetches existing rules for the domain to ensure consistency.",
|
|
2419
|
+
{
|
|
2420
|
+
observation: z6.string().describe("What you observed or discovered (e.g. 'Suppliers can have multiple org types in Gateway')"),
|
|
2421
|
+
domain: z6.string().describe("Which domain this rule belongs to (e.g. 'Governance & Decision-Making')")
|
|
2422
|
+
},
|
|
2423
|
+
async ({ observation, domain }) => {
|
|
2424
|
+
const allRules = await mcpQuery("kb.listEntries", { collectionSlug: "business-rules" });
|
|
2425
|
+
const existingRules = allRules.filter((r) => r.data?.domain === domain);
|
|
2426
|
+
const existingContext = existingRules.length > 0 ? existingRules.map((r) => `${r.entryId ?? ""}: ${r.name} [${r.status}] \u2014 ${r.data?.description ?? ""}`).join("\n") : "No existing rules for this domain.";
|
|
2427
|
+
const highestRuleNum = allRules.map((r) => parseInt((r.entryId ?? "").replace(/^[A-Z]+-/, ""), 10)).filter((n) => !isNaN(n)).sort((a, b) => b - a)[0] || 0;
|
|
2428
|
+
const nextRuleId = `SOS-${String(highestRuleNum + 1).padStart(3, "0")}`;
|
|
2429
|
+
return {
|
|
2430
|
+
messages: [
|
|
2431
|
+
{
|
|
2432
|
+
role: "user",
|
|
2433
|
+
content: {
|
|
2434
|
+
type: "text",
|
|
2435
|
+
text: `Draft a business rule based on this observation:
|
|
2436
|
+
|
|
2437
|
+
"${observation}"
|
|
2438
|
+
|
|
2439
|
+
Domain: ${domain}
|
|
2440
|
+
Suggested rule ID: ${nextRuleId}
|
|
2441
|
+
|
|
2442
|
+
Existing rules in this domain:
|
|
2443
|
+
${existingContext}
|
|
2444
|
+
|
|
2445
|
+
Draft the rule with these fields:
|
|
2446
|
+
1. **entryId**: ${nextRuleId}
|
|
2447
|
+
2. **name**: Concise rule title
|
|
2448
|
+
3. **data.description**: What the rule states
|
|
2449
|
+
4. **data.rationale**: Why this rule matters
|
|
2450
|
+
5. **data.dataImpact**: How this affects data models, APIs, or storage
|
|
2451
|
+
6. **data.severity**: high / medium / low
|
|
2452
|
+
7. **data.platforms**: Which platforms are affected
|
|
2453
|
+
8. **data.relatedRules**: Any related existing rules
|
|
2454
|
+
|
|
2455
|
+
Make sure the rule is consistent with existing rules and doesn't contradict them. After drafting, I can create it using the create-entry tool with collection "business-rules".`
|
|
2456
|
+
}
|
|
2457
|
+
}
|
|
2458
|
+
]
|
|
2459
|
+
};
|
|
2460
|
+
}
|
|
2461
|
+
);
|
|
2462
|
+
}
|
|
2463
|
+
|
|
2464
|
+
// src/index.ts
|
|
2465
|
+
if (!process.env.CONVEX_SITE_URL && !process.env.PRODUCTBRAIN_API_KEY) {
|
|
2466
|
+
try {
|
|
2467
|
+
const envPath = resolve2(process.cwd(), ".env.mcp");
|
|
2468
|
+
for (const line of readFileSync2(envPath, "utf-8").split("\n")) {
|
|
2469
|
+
const trimmed = line.trim();
|
|
2470
|
+
if (!trimmed || trimmed.startsWith("#")) continue;
|
|
2471
|
+
const eqIdx = trimmed.indexOf("=");
|
|
2472
|
+
if (eqIdx === -1) continue;
|
|
2473
|
+
process.env[trimmed.slice(0, eqIdx)] ??= trimmed.slice(eqIdx + 1);
|
|
2474
|
+
}
|
|
2475
|
+
} catch {
|
|
2476
|
+
}
|
|
2477
|
+
}
|
|
2478
|
+
bootstrapCloudMode();
|
|
2479
|
+
var SERVER_VERSION = "1.0.0";
|
|
2480
|
+
initAnalytics();
|
|
2481
|
+
var workspaceId;
|
|
2482
|
+
try {
|
|
2483
|
+
workspaceId = await getWorkspaceId();
|
|
2484
|
+
} catch (err) {
|
|
2485
|
+
const hint = !process.env.PRODUCTBRAIN_API_KEY && !process.env.CONVEX_SITE_URL ? "\n[MCP] Hint: Set PRODUCTBRAIN_API_KEY in your MCP config env block. Get your key at SynergyOS \u2192 Settings \u2192 API Keys." : "";
|
|
2486
|
+
process.stderr.write(`[MCP] Startup failed: ${err.message}${hint}
|
|
2487
|
+
`);
|
|
2488
|
+
process.exit(1);
|
|
2489
|
+
}
|
|
2490
|
+
trackSessionStarted(
|
|
2491
|
+
process.env.WORKSPACE_SLUG ?? "unknown",
|
|
2492
|
+
workspaceId,
|
|
2493
|
+
SERVER_VERSION
|
|
2494
|
+
);
|
|
2495
|
+
var server = new McpServer2(
|
|
2496
|
+
{
|
|
2497
|
+
name: "Product Brain",
|
|
2498
|
+
version: SERVER_VERSION
|
|
2499
|
+
},
|
|
2500
|
+
{
|
|
2501
|
+
capabilities: { logging: {} },
|
|
2502
|
+
instructions: [
|
|
2503
|
+
"ProductBrain \u2014 the single source of truth for product knowledge.",
|
|
2504
|
+
"Terminology, standards, and core data all live here \u2014 no need to check external docs.",
|
|
2505
|
+
"",
|
|
2506
|
+
"Terminology & naming: For 'what is X?' or naming questions, fetch `productbrain://terminology`",
|
|
2507
|
+
"or use the `name-check` prompt to validate names against the glossary.",
|
|
2508
|
+
"",
|
|
2509
|
+
"Workflow:",
|
|
2510
|
+
" 1. Verify: call `health` to confirm connectivity.",
|
|
2511
|
+
" 2. Terminology: fetch `productbrain://terminology` or use `name-check` prompt for naming questions.",
|
|
2512
|
+
" 3. Discover: use `kb-search` to find entries by text, or `list-entries` to browse a collection.",
|
|
2513
|
+
" 4. Drill in: use `get-entry` for full details \u2014 data, labels, relations, history.",
|
|
2514
|
+
" 5. Capture: use `smart-capture` to create entries \u2014 it auto-links related entries and",
|
|
2515
|
+
" returns a quality scorecard in one call. Use `create-entry` only when you need",
|
|
2516
|
+
" full control over every field.",
|
|
2517
|
+
" 6. Connect: use `suggest-links` then `relate-entries` to build the graph.",
|
|
2518
|
+
" 7. Quality: use `quality-check` to assess entry completeness.",
|
|
2519
|
+
" 8. Debug: use `mcp-audit` to see what backend calls happened this session.",
|
|
2520
|
+
"",
|
|
2521
|
+
"Always prefer `smart-capture` over `create-entry` or `quick-capture` for new entries.",
|
|
2522
|
+
"Always prefer kb-search or list-entries before get-entry \u2014 discover, then drill in.",
|
|
2523
|
+
"",
|
|
2524
|
+
"Orientation:",
|
|
2525
|
+
" When you need to understand the system \u2014 architecture, data model, rules,",
|
|
2526
|
+
" or analytics \u2014 fetch the `productbrain://orientation` resource first.",
|
|
2527
|
+
" It gives you the map. Then use the appropriate tool to drill in."
|
|
2528
|
+
].join("\n")
|
|
2529
|
+
}
|
|
2530
|
+
);
|
|
2531
|
+
registerKnowledgeTools(server);
|
|
2532
|
+
registerLabelTools(server);
|
|
2533
|
+
registerHealthTools(server);
|
|
2534
|
+
registerVerifyTools(server);
|
|
2535
|
+
registerSmartCaptureTools(server);
|
|
2536
|
+
registerResources(server);
|
|
2537
|
+
registerPrompts(server);
|
|
2538
|
+
var transport = new StdioServerTransport();
|
|
2539
|
+
await server.connect(transport);
|
|
2540
|
+
async function gracefulShutdown() {
|
|
2541
|
+
await shutdownAnalytics();
|
|
2542
|
+
process.exit(0);
|
|
2543
|
+
}
|
|
2544
|
+
process.on("SIGINT", gracefulShutdown);
|
|
2545
|
+
process.on("SIGTERM", gracefulShutdown);
|
|
2546
|
+
//# sourceMappingURL=index.js.map
|