@intentius/behold 0.32.0 → 0.33.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/AGENTS.md +64 -3133
- package/README.md +17 -6
- package/dist/chant-KLLNQOCK.js +117 -0
- package/dist/choudoufu-chant-read-MJ6DK23L.js +36 -0
- package/dist/chunk-26K6QLVB.js +157 -0
- package/dist/chunk-4IETG5U7.js +267 -0
- package/dist/chunk-7DQDWJI5.js +46 -0
- package/dist/chunk-ANJ33KX4.js +78 -0
- package/dist/chunk-C7OMVDI5.js +124 -0
- package/dist/chunk-GG3SLEYM.js +30297 -0
- package/dist/chunk-GMCRBXPQ.js +15578 -0
- package/dist/chunk-IMX6PXXA.js +1019 -0
- package/dist/chunk-JHLNY324.js +232 -0
- package/dist/chunk-JJPU2DXX.js +54 -0
- package/dist/chunk-KUHU6T4P.js +2820 -0
- package/dist/chunk-OY4EF7ZO.js +5651 -0
- package/dist/chunk-XKWCGNT2.js +8139 -0
- package/dist/chunk-YO233FHU.js +136 -0
- package/dist/cli.js +859 -77499
- package/dist/config-XKQQ4ORG.js +69 -0
- package/dist/config-run-4IMSAYPX.js +418 -0
- package/dist/declaration-5NE7H5UD.js +6867 -0
- package/dist/index.js +99 -0
- package/dist/main-4PGA5RJS.js +2509 -0
- package/dist/mcp-W2CHVEPI.js +753 -0
- package/dist/object-store-H77QSRIZ.js +1033 -0
- package/dist/src-54PT4UC5.js +1189 -0
- package/dist/tree-W23HE2EZ.js +17 -0
- package/example-choudoufu-estate/chant.workspace.json +1 -1
- package/example-terraform-estate/README.md +2 -2
- package/example-terraform-estate/chant.workspace.json +1 -1
- package/example-three-cloud/chant.workspace.json +2 -2
- package/example-three-cloud/package-lock.json +32 -515
- package/example-three-cloud/package.json +5 -5
- package/package.json +18 -16
|
@@ -0,0 +1,753 @@
|
|
|
1
|
+
import {
|
|
2
|
+
DEFAULT_LINK_BASE,
|
|
3
|
+
findServe,
|
|
4
|
+
localCapabilities,
|
|
5
|
+
localGraph,
|
|
6
|
+
localSearch,
|
|
7
|
+
realDir,
|
|
8
|
+
shotFromArgs,
|
|
9
|
+
within
|
|
10
|
+
} from "./chunk-GG3SLEYM.js";
|
|
11
|
+
import "./chunk-JJPU2DXX.js";
|
|
12
|
+
import {
|
|
13
|
+
FORGE_BUDGETS,
|
|
14
|
+
ReadGraphError,
|
|
15
|
+
RevisionError,
|
|
16
|
+
cutChanged,
|
|
17
|
+
cutDocument,
|
|
18
|
+
documentOptions,
|
|
19
|
+
emptyDocument,
|
|
20
|
+
gitRoot,
|
|
21
|
+
graphDocument,
|
|
22
|
+
graphView,
|
|
23
|
+
mermaidDiagram,
|
|
24
|
+
parseRange,
|
|
25
|
+
readAtRevision,
|
|
26
|
+
resolveRange,
|
|
27
|
+
rootTable
|
|
28
|
+
} from "./chunk-XKWCGNT2.js";
|
|
29
|
+
import "./chunk-26K6QLVB.js";
|
|
30
|
+
import "./chunk-4IETG5U7.js";
|
|
31
|
+
import "./chunk-OY4EF7ZO.js";
|
|
32
|
+
import "./chunk-ANJ33KX4.js";
|
|
33
|
+
import "./chunk-KUHU6T4P.js";
|
|
34
|
+
import "./chunk-7DQDWJI5.js";
|
|
35
|
+
|
|
36
|
+
// src/mcp.ts
|
|
37
|
+
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
|
|
38
|
+
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
|
39
|
+
import { CallToolRequestSchema, ListResourcesRequestSchema, ListToolsRequestSchema, ReadResourceRequestSchema } from "@modelcontextprotocol/sdk/types.js";
|
|
40
|
+
import { existsSync as existsSync2, readFileSync as readFileSync2, statSync } from "node:fs";
|
|
41
|
+
import { dirname as dirname2, join as join2, relative, resolve, sep } from "node:path";
|
|
42
|
+
import { fileURLToPath as fileURLToPath2 } from "node:url";
|
|
43
|
+
|
|
44
|
+
// src/mcp-graph.ts
|
|
45
|
+
var GraphToolError = class extends Error {
|
|
46
|
+
constructor(message, body) {
|
|
47
|
+
super(message);
|
|
48
|
+
this.body = body;
|
|
49
|
+
}
|
|
50
|
+
body;
|
|
51
|
+
};
|
|
52
|
+
function rootCount(doc) {
|
|
53
|
+
const ids = new Set(doc.groups.map((g) => g.id));
|
|
54
|
+
return doc.groups.filter((g) => g.parent === void 0 || !ids.has(g.parent)).length;
|
|
55
|
+
}
|
|
56
|
+
function namedBoxes(doc, ids) {
|
|
57
|
+
const known = /* @__PURE__ */ new Set([...doc.nodes.map((n) => n.id), ...doc.groups.map((g) => g.id)]);
|
|
58
|
+
return ids.flatMap((id) => {
|
|
59
|
+
if (known.has(id)) return [id];
|
|
60
|
+
const byTitle = doc.groups.filter((g) => g.title === id).map((g) => g.id);
|
|
61
|
+
if (byTitle.length) return byTitle;
|
|
62
|
+
const byRoot = [...new Set(doc.nodes.filter((n) => n.detail__root === id && n.box !== void 0).map((n) => n.box))];
|
|
63
|
+
return byRoot.length ? byRoot : [id];
|
|
64
|
+
});
|
|
65
|
+
}
|
|
66
|
+
async function readGraphCut(req, behold) {
|
|
67
|
+
if (req.around && req.changed) throw new GraphToolError("around and changed are two cuts; give one");
|
|
68
|
+
if (req.direction && !req.around) throw new GraphToolError("direction goes with around");
|
|
69
|
+
try {
|
|
70
|
+
if (req.changed) {
|
|
71
|
+
const range = parseRange(req.changed);
|
|
72
|
+
if ("error" in range) throw new GraphToolError(range.error);
|
|
73
|
+
const root = gitRoot(req.dir);
|
|
74
|
+
const { base, head } = resolveRange(root, range);
|
|
75
|
+
const opts = { alike: false, detail: 3, behold, source: false };
|
|
76
|
+
const headRead = await readAtRevision(root, req.dir, head, opts);
|
|
77
|
+
if (!headRead) throw new GraphToolError(`${req.dir} does not exist at ${range.head} (${head.slice(0, 10)})`);
|
|
78
|
+
const baseRead = await readAtRevision(root, req.dir, base, opts);
|
|
79
|
+
const before = baseRead?.document ?? emptyDocument(headRead.document, base);
|
|
80
|
+
const after = headRead.document;
|
|
81
|
+
const document = cutChanged(before, after, {
|
|
82
|
+
base: range.mergeBase ? `${range.base}...` : range.base,
|
|
83
|
+
head: range.head,
|
|
84
|
+
...req.depth !== void 0 ? { depth: req.depth } : {}
|
|
85
|
+
});
|
|
86
|
+
return { document, whole: { cards: after.nodes.length, edges: after.edges.length, roots: rootCount(after) } };
|
|
87
|
+
}
|
|
88
|
+
const view = await graphView(req.dir, { alike: true });
|
|
89
|
+
const options = documentOptions({ projectDir: req.dir, ...view.read.workspace ? { workspace: view.read.workspace } : {}, behold });
|
|
90
|
+
const whole = graphDocument({ view, document: options, source: false });
|
|
91
|
+
const counts = { cards: whole.nodes.length, edges: whole.edges.length, roots: rootCount(whole) };
|
|
92
|
+
if (!req.around) return { document: whole, whole: counts };
|
|
93
|
+
const r = cutDocument(whole, namedBoxes(whole, req.around), { ...req.depth !== void 0 ? { depth: req.depth } : {}, ...req.direction ? { direction: req.direction } : {} });
|
|
94
|
+
if (!r.ok) throw new GraphToolError(r.error, { missing: r.missing });
|
|
95
|
+
return { document: r.document, whole: counts };
|
|
96
|
+
} catch (err) {
|
|
97
|
+
if (err instanceof ReadGraphError) throw new GraphToolError(`${err.refusal.error} ${err.refusal.remedy}`.trim());
|
|
98
|
+
if (err instanceof RevisionError) throw new GraphToolError(`${err.message}${err.remedy ? ` ${err.remedy}` : ""}`);
|
|
99
|
+
throw err;
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
var TEXT_CHARS = 18e3;
|
|
103
|
+
var MCP_MERMAID_BUDGET = {
|
|
104
|
+
...FORGE_BUDGETS.github,
|
|
105
|
+
blockChars: 9e3,
|
|
106
|
+
maxEdges: 120,
|
|
107
|
+
commentChars: TEXT_CHARS,
|
|
108
|
+
confirmed: false,
|
|
109
|
+
basis: "behold#1073: a tool result that stays well under Claude Code's 10,000-token warning"
|
|
110
|
+
};
|
|
111
|
+
var plural = (n, one, many = `${one}s`) => `${n} ${n === 1 ? one : many}`;
|
|
112
|
+
function cutSentence(r, doc) {
|
|
113
|
+
const depth = r.depth ?? 1;
|
|
114
|
+
if (r.around) {
|
|
115
|
+
const way = r.direction === "up" ? "what they depend on" : r.direction === "down" ? "what depends on them" : "both ways";
|
|
116
|
+
return `Cut around ${r.around.join(", ")}, ${plural(depth, "hop")} ${way}: ${plural(doc.nodes.length, "card")}, ${plural(doc.edges.length, "edge")}.`;
|
|
117
|
+
}
|
|
118
|
+
if (r.changed) return `Cut to what changed in ${r.changed}, with cards within ${plural(depth, "hop")}: ${plural(doc.nodes.length, "card")}, ${plural(doc.edges.length, "edge")}.`;
|
|
119
|
+
return "The whole graph.";
|
|
120
|
+
}
|
|
121
|
+
function graphText(i) {
|
|
122
|
+
const { document: doc, whole } = i.read;
|
|
123
|
+
const lines = [];
|
|
124
|
+
lines.push(`behold graph of ${i.dir}: ${plural(whole.roots, "top-level box", "top-level boxes")} (roots and members), ${plural(whole.cards, "card")}, ${plural(whole.edges, "edge")} in all.`);
|
|
125
|
+
lines.push(cutSentence(i.request, doc));
|
|
126
|
+
for (const n of doc.notes.slice(0, 4)) lines.push(n.text.length > 240 ? `${n.text.slice(0, 237)}...` : n.text);
|
|
127
|
+
const head = `${lines.join("\n")}
|
|
128
|
+
|
|
129
|
+
`;
|
|
130
|
+
const tail = i.link.serving ? `
|
|
131
|
+
Open it in behold: ${i.link.url}
|
|
132
|
+
` : `
|
|
133
|
+
No behold serve of this project is running. Start \`${i.link.command}\` and open ${i.link.url}
|
|
134
|
+
`;
|
|
135
|
+
const room = TEXT_CHARS - head.length - tail.length;
|
|
136
|
+
const d = mermaidDiagram(doc, { budget: { ...MCP_MERMAID_BUDGET, blockChars: Math.min(MCP_MERMAID_BUDGET.blockChars, Math.max(0, Math.floor(room / 2))) } });
|
|
137
|
+
let body;
|
|
138
|
+
if (d.text && d.hidden === 0 && d.text.length + 24 <= room) {
|
|
139
|
+
body = `\`\`\`mermaid
|
|
140
|
+
${d.text}\`\`\`
|
|
141
|
+
`;
|
|
142
|
+
} else {
|
|
143
|
+
const hint = i.request.around ? "" : " Ask again with around set to a root or a card id to see one part as a diagram.";
|
|
144
|
+
const intro = `The diagram does not fit in this answer (${plural(doc.nodes.length, "card")}), so the roots are listed with their card counts.${hint}
|
|
145
|
+
|
|
146
|
+
`;
|
|
147
|
+
body = `${intro}${rootTable(doc, Math.max(0, room - intro.length))}`;
|
|
148
|
+
}
|
|
149
|
+
return `${head}${body}${tail}`;
|
|
150
|
+
}
|
|
151
|
+
function viewQuery(request, doc) {
|
|
152
|
+
const first = request.around?.[0];
|
|
153
|
+
if (!first) return {};
|
|
154
|
+
return doc.nodes.some((n) => n.id === first) ? { node: first } : { focus: request.around.join(",") };
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
// src/viewer-resource.ts
|
|
158
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
159
|
+
import { dirname, join } from "node:path";
|
|
160
|
+
import { fileURLToPath } from "node:url";
|
|
161
|
+
var VIEWER_URI = "ui://behold/viewer";
|
|
162
|
+
var APP_MIME = "text/html;profile=mcp-app";
|
|
163
|
+
var PLACEHOLDER_HTML = `<!doctype html>
|
|
164
|
+
<html lang="en">
|
|
165
|
+
<head>
|
|
166
|
+
<meta charset="utf-8">
|
|
167
|
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
168
|
+
<title>behold graph</title>
|
|
169
|
+
<style>
|
|
170
|
+
:root { color-scheme: light dark; }
|
|
171
|
+
body { font: 14px/1.5 system-ui, sans-serif; margin: 0; padding: 16px; }
|
|
172
|
+
</style>
|
|
173
|
+
</head>
|
|
174
|
+
<body>
|
|
175
|
+
<p>The interactive graph view is not in this build of behold. The answer above holds the same graph as a diagram or a table, and a link to open it in behold.</p>
|
|
176
|
+
</body>
|
|
177
|
+
</html>
|
|
178
|
+
`;
|
|
179
|
+
var VIEWER_BUILD = join("dist", "behold-viewer", "viewer.html");
|
|
180
|
+
function loadViewer(root = join(dirname(fileURLToPath(import.meta.url)), "..")) {
|
|
181
|
+
const file = join(root, VIEWER_BUILD);
|
|
182
|
+
try {
|
|
183
|
+
if (existsSync(file)) return { html: readFileSync(file, "utf8"), kind: "viewer" };
|
|
184
|
+
} catch {
|
|
185
|
+
}
|
|
186
|
+
return { html: PLACEHOLDER_HTML, kind: "placeholder" };
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
// src/mcp.ts
|
|
190
|
+
var DEFAULT_SERVE_URL = "http://127.0.0.1:4600";
|
|
191
|
+
var serveCommand = (dir) => `npx @intentius/behold serve ${dir}`;
|
|
192
|
+
var ToolError = class extends Error {
|
|
193
|
+
constructor(message, body) {
|
|
194
|
+
super(message);
|
|
195
|
+
this.body = body;
|
|
196
|
+
}
|
|
197
|
+
body;
|
|
198
|
+
};
|
|
199
|
+
var WRITE_WORDS = ["deploy", "apply", "approve", "run", "op", "rollback", "roll", "revert", "write", "delete", "destroy", "sync", "exec", "merge", "push", "commit", "publish", "override", "unlock", "migrate", "put", "create", "update", "trigger"];
|
|
200
|
+
function writeWord(name) {
|
|
201
|
+
const parts = name.replace(/([a-z])([A-Z])/g, "$1 $2").toLowerCase().split(/[^a-z]+/).filter(Boolean);
|
|
202
|
+
return WRITE_WORDS.find((w) => parts.some((p) => p === w || p === `${w}s` || w.length >= 4 && p.startsWith(w)));
|
|
203
|
+
}
|
|
204
|
+
function assertNoWrites(tools) {
|
|
205
|
+
for (const t of tools) {
|
|
206
|
+
const w = writeWord(t.name);
|
|
207
|
+
if (w) throw new Error(`behold mcp never deploys, applies, approves, runs an Op, rolls back or writes, and the tool ${t.name} would ${w}; it is not served`);
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
function refusal(name) {
|
|
211
|
+
const w = writeWord(name);
|
|
212
|
+
const what = w ? `${name} would ${w}, and ` : `there is no tool ${name}; `;
|
|
213
|
+
return `behold mcp draws and never changes anything: ${what}it serves capabilities, ask, show and shot only. Deploys, approvals, Ops and rollbacks belong to a person in behold's panel or at a shell. Ask estate questions with ask, after reading the catalog with capabilities.`;
|
|
214
|
+
}
|
|
215
|
+
var CREDENTIAL = /token|secret|password|passwd|credential|key|auth|session|cookie|signature|sas/i;
|
|
216
|
+
function checkArgs(tool, args) {
|
|
217
|
+
const a = args ?? {};
|
|
218
|
+
const s = tool.inputSchema;
|
|
219
|
+
for (const k of Object.keys(a)) {
|
|
220
|
+
if (Object.hasOwn(s.properties, k)) continue;
|
|
221
|
+
if (CREDENTIAL.test(k)) throw new ToolError(`${tool.name} takes no ${k}: behold mcp never takes a credential; the serve reads with the credentials it was started with`);
|
|
222
|
+
throw new ToolError(`${tool.name} takes no argument ${k} (it takes ${Object.keys(s.properties).join(", ") || "none"})`);
|
|
223
|
+
}
|
|
224
|
+
for (const k of s.required ?? []) if (a[k] === void 0) throw new ToolError(`${tool.name} needs ${k}`);
|
|
225
|
+
for (const [k, p] of Object.entries(s.properties)) {
|
|
226
|
+
const v = a[k];
|
|
227
|
+
if (v === void 0) continue;
|
|
228
|
+
if (p.type === "string") {
|
|
229
|
+
if (typeof v !== "string") throw new ToolError(`${tool.name}: ${k} must be a string`);
|
|
230
|
+
if (p.enum && !p.enum.includes(v)) throw new ToolError(`${tool.name}: ${k} is one of ${p.enum.join(", ")}`);
|
|
231
|
+
}
|
|
232
|
+
if (p.type === "boolean" && typeof v !== "boolean") throw new ToolError(`${tool.name}: ${k} must be true or false`);
|
|
233
|
+
if (p.type === "integer" && !(Number.isInteger(v) && (p.minimum === void 0 || v >= p.minimum) && (p.maximum === void 0 || v <= p.maximum))) {
|
|
234
|
+
throw new ToolError(`${tool.name}: ${k} must be a whole number${p.minimum !== void 0 ? ` from ${p.minimum}` : ""}${p.maximum !== void 0 ? ` to ${p.maximum}` : ""}`);
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
return a;
|
|
238
|
+
}
|
|
239
|
+
var trimUrl = (u) => u.replace(/\/+$/, "");
|
|
240
|
+
async function servedProject(fetch, url) {
|
|
241
|
+
try {
|
|
242
|
+
const res = await fetch(`${trimUrl(url)}/api/project`, { headers: { accept: "application/json" }, signal: AbortSignal.timeout(1e4) });
|
|
243
|
+
if (!res.ok) return void 0;
|
|
244
|
+
const body = await res.json();
|
|
245
|
+
if (typeof body.projectDir !== "string") return void 0;
|
|
246
|
+
const dirs = Array.isArray(body.projectDirs) ? body.projectDirs.filter((d) => typeof d === "string") : [];
|
|
247
|
+
return { projectDir: body.projectDir, projectDirs: dirs };
|
|
248
|
+
} catch {
|
|
249
|
+
return void 0;
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
async function locateServe(o) {
|
|
253
|
+
const entry = o.url ? void 0 : (o.registry ?? findServe)(o.projectDir);
|
|
254
|
+
const url = o.url ?? entry?.url ?? DEFAULT_SERVE_URL;
|
|
255
|
+
const via = o.url ? "url" : entry ? "registry" : "default";
|
|
256
|
+
const p = await servedProject(o.fetch, url);
|
|
257
|
+
if (!p) return void 0;
|
|
258
|
+
const dirs = [p.projectDir, ...p.projectDirs, ...entry ? [entry.projectDir] : []].map(realDir);
|
|
259
|
+
const ours = via === "url" && !o.projectGiven || dirs.some((d) => within(d, o.projectDir));
|
|
260
|
+
return { url: trimUrl(url), via, serves: p.projectDir, ours };
|
|
261
|
+
}
|
|
262
|
+
var json = (value) => ({ content: [{ type: "text", text: JSON.stringify(value, null, 2) }] });
|
|
263
|
+
var failed = (message, body) => ({
|
|
264
|
+
isError: true,
|
|
265
|
+
content: [{ type: "text", text: body ? JSON.stringify({ error: message, ...body }, null, 2) : message }]
|
|
266
|
+
});
|
|
267
|
+
var SEARCH_OPTIONS = "The query is chant's search grammar, unchanged (https://intentius.io/chant/cli/search/). env reads that environment live (chant search --live --env <env>); snapshot with env replays a recorded snapshot instead (chant --snapshot <ref>, such as latest); chant's --explain is always on, for the near-misses drawn. It takes no --check-live or --check-snapshot (drift is not drawn), and no --ambient, --src or --fail-on-drift. Read the capabilities tool first: it lists the capabilities a cap: term asks (cap:internet-reachable(22), ->[cap=network]), each one's meaning, parameters and rule (INTENTIUS/chant#4375).";
|
|
268
|
+
var VIEW_PROPS = {
|
|
269
|
+
query: { type: "string", description: "A chant search query whose matches the view lights, such as `attr:internetFacing=true`." },
|
|
270
|
+
env: { type: "string", description: "The environment whose live state the view shows. Without it, the declared source." },
|
|
271
|
+
snapshot: { type: "string", description: "With env: a recorded snapshot to show instead of a live read (latest, or a ref chant lists). Not with plan." },
|
|
272
|
+
plan: {
|
|
273
|
+
type: "boolean",
|
|
274
|
+
description: "The plan read (behold#922): the query is answered at the plan depth (CHANT_TERRAFORM_OBSERVE=plan, chant search --live --env), and the cards carry each Terraform root's planAction, planActions, planReplacePaths and planActionReason. On a bare Terraform folder no env is needed; on a chant project pass env. Refused with snapshot. Runs terraform plan -lock=false in each root: it changes nothing, and reads every resource."
|
|
275
|
+
},
|
|
276
|
+
countBy: {
|
|
277
|
+
type: "string",
|
|
278
|
+
description: "Group the matches the way chant search --count-by does: kind, module or attr:<name> (behold#922). The answer is chant's groups and total; the view lights each group's cards and labels the group with its count. The query may then be empty, to count the whole estate."
|
|
279
|
+
},
|
|
280
|
+
member: { type: "string", description: "Show one estate member." },
|
|
281
|
+
zoom: { type: "string", description: "The zoom: components, resources, attributes, or another behold offers." },
|
|
282
|
+
focus: { type: "string", description: "Comma-separated box ids to keep at full weight; the rest dims." },
|
|
283
|
+
node: { type: "string", description: "A card to select, by behold's node id." }
|
|
284
|
+
};
|
|
285
|
+
var VIEW_ARGS = ["member", "zoom", "focus", "node"];
|
|
286
|
+
function viewOf(a) {
|
|
287
|
+
const v = {};
|
|
288
|
+
if (typeof a.query === "string" && a.query.trim()) v.q = a.query;
|
|
289
|
+
if (typeof a.env === "string" && a.env) v.env = a.env;
|
|
290
|
+
if (typeof a.snapshot === "string" && a.snapshot) v.snapshot = a.snapshot;
|
|
291
|
+
if (a.plan === true) v.plan = "1";
|
|
292
|
+
if (typeof a.countBy === "string" && a.countBy) v.countBy = a.countBy;
|
|
293
|
+
if (v.plan && v.snapshot) throw new ToolError("plan and snapshot were both asked: a plan is read now, and a snapshot replays what was recorded. Drop one.");
|
|
294
|
+
for (const k of VIEW_ARGS) if (typeof a[k] === "string" && a[k]) v[k] = a[k];
|
|
295
|
+
if (v.snapshot && !v.env) throw new ToolError("snapshot needs env: a snapshot is recorded per environment");
|
|
296
|
+
return v;
|
|
297
|
+
}
|
|
298
|
+
var READ_ONLY = { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false };
|
|
299
|
+
function askAnswer(status, body) {
|
|
300
|
+
const doc = body.document;
|
|
301
|
+
if (!doc || typeof doc !== "object" || Array.isArray(doc)) {
|
|
302
|
+
throw new ToolError(typeof body.error === "string" ? body.error : `GET /api/search answered ${status}`, { status, ...body });
|
|
303
|
+
}
|
|
304
|
+
const failed2 = "error" in doc;
|
|
305
|
+
return { doc: { ...doc, link: typeof body.link === "string" ? body.link : null, drawn: false }, failed: failed2 };
|
|
306
|
+
}
|
|
307
|
+
var CYPHER_HELP = "A read-only Cypher query over the graph pane's database (behold#1027): every member's chant IR, every engine graph document (choudoufu, plunge) and every index version, in one LadybugDB. Tables: Resource(key, source, scopeKey, version, id, kind, lexicon, listedType, location, nativeId, name, address, ownership, attrs, tags, facts, observedAt) keyed <member>/<id> as chant workspace search prints it; CloudId(value, kind) with (Resource)-[:KNOWN_AS]->(CloudId), so the same object in two sources is two hops; (Resource)-[:REF {kind, viaAttr, toAttr, grain, origin, rule, relation, ambiguous}]->(Resource), origin derived for an identity match. attrs, tags and facts are JSON strings. Anything that writes (CREATE, MERGE, SET, DELETE, COPY, LOAD, CALL ...) is refused. Needs the optional peer @ladybugdb/core; without it ask refuses with the install line. Example: MATCH (a:Resource)-[:KNOWN_AS]->(c:CloudId)<-[:KNOWN_AS]-(b:Resource) WHERE a.scopeKey <> b.scopeKey RETURN a.key, b.key, c.value";
|
|
308
|
+
function jsonObjectArg(raw, name) {
|
|
309
|
+
if (raw === void 0) return void 0;
|
|
310
|
+
let v;
|
|
311
|
+
try {
|
|
312
|
+
v = JSON.parse(String(raw));
|
|
313
|
+
} catch {
|
|
314
|
+
throw new ToolError(`${name} is a JSON object`);
|
|
315
|
+
}
|
|
316
|
+
if (!v || typeof v !== "object" || Array.isArray(v)) throw new ToolError(`${name} is a JSON object`);
|
|
317
|
+
return v;
|
|
318
|
+
}
|
|
319
|
+
async function askGraph(a, ctx) {
|
|
320
|
+
const asked = ["query", "cypher", "resource", "countBy"].filter((k) => typeof a[k] === "string" && a[k]);
|
|
321
|
+
if (asked.length > 1) throw new ToolError(`ask takes one of query, cypher or resource, and was given ${asked.join(" and ")}`);
|
|
322
|
+
for (const k of ["env", "snapshot", "plan", "show"]) if (a[k] !== void 0) throw new ToolError(`${k} goes with a chant search query, not with cypher or resource`);
|
|
323
|
+
let path;
|
|
324
|
+
const q = new URLSearchParams();
|
|
325
|
+
if (typeof a.cypher === "string") {
|
|
326
|
+
if (a.template !== void 0 || a.inputs !== void 0) throw new ToolError("template and inputs go with resource");
|
|
327
|
+
if (!a.cypher.trim()) throw new ToolError("cypher is empty");
|
|
328
|
+
path = "query";
|
|
329
|
+
q.set("cypher", a.cypher);
|
|
330
|
+
const params = jsonObjectArg(a.params, "params");
|
|
331
|
+
if (params) q.set("params", JSON.stringify(params));
|
|
332
|
+
} else {
|
|
333
|
+
if (a.params !== void 0) throw new ToolError("params goes with cypher");
|
|
334
|
+
const ref = String(a.resource ?? "").trim();
|
|
335
|
+
if (!ref) throw new ToolError("resource is empty");
|
|
336
|
+
if (typeof a.template === "string") {
|
|
337
|
+
const resolved = await graphRoute(ctx, "resolve", new URLSearchParams({ ref }));
|
|
338
|
+
const cands = Array.isArray(resolved.body.candidates) ? resolved.body.candidates : [];
|
|
339
|
+
if (resolved.status !== 200) throw new ToolError(typeof resolved.body.error === "string" ? resolved.body.error : `resolve answered ${resolved.status}`, resolved.body);
|
|
340
|
+
if (cands.length !== 1 || typeof cands[0].key !== "string") {
|
|
341
|
+
throw new ToolError(`${ref} resolves to ${cands.length} nodes, so the template has no one node to run on; ask with the key of one`, { candidates: cands, sources: resolved.body.sources });
|
|
342
|
+
}
|
|
343
|
+
path = "template";
|
|
344
|
+
q.set("name", a.template);
|
|
345
|
+
q.set("node", cands[0].key);
|
|
346
|
+
const inputs = jsonObjectArg(a.inputs, "inputs") ?? {};
|
|
347
|
+
for (const [k, v] of Object.entries(inputs)) {
|
|
348
|
+
if (typeof v !== "string") throw new ToolError(`input ${k} is a string`);
|
|
349
|
+
q.set(`in.${k}`, v);
|
|
350
|
+
}
|
|
351
|
+
} else {
|
|
352
|
+
if (a.inputs !== void 0) throw new ToolError("inputs goes with template");
|
|
353
|
+
path = "resolve";
|
|
354
|
+
q.set("ref", ref);
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
const { status, body, serve } = await graphRoute(ctx, path, q);
|
|
358
|
+
if (status !== 200) throw new ToolError(typeof body.error === "string" ? body.error : `GET /api/graphdb/${path} answered ${status}`, { status, ...body });
|
|
359
|
+
const note = serve ? `Nothing is drawn: ask never moves the tab. show with the link's node and focus draws it in the open tab at ${serve}.` : `Nothing is drawn: no behold serve of ${ctx.projectDir} was running, so behold answered in this process. Start \`${serveCommand(ctx.projectDir)}\` to see it.`;
|
|
360
|
+
return { content: [{ type: "text", text: JSON.stringify({ ...body, drawn: false }) }, { type: "text", text: note }] };
|
|
361
|
+
}
|
|
362
|
+
async function graphRoute(ctx, path, q) {
|
|
363
|
+
const serve = await ctx.findServe();
|
|
364
|
+
if (serve?.ours) {
|
|
365
|
+
const res = await ctx.fetch(`${serve.url}/api/graphdb/${path}?${q}`, { headers: { accept: "application/json" } });
|
|
366
|
+
return { status: res.status, body: await res.json().catch(() => ({})), serve: serve.url };
|
|
367
|
+
}
|
|
368
|
+
const local = ctx.localGraph ?? ((p, query) => localGraph(ctx.projectDir, p, query));
|
|
369
|
+
return local(path, q);
|
|
370
|
+
}
|
|
371
|
+
var GRAPH_PROPS = {
|
|
372
|
+
dir: { type: "string", description: "A folder inside the project to read, relative to it (default: the project folder)." },
|
|
373
|
+
around: { type: "string", description: "Comma-separated card or box ids to cut around (a root such as a Terraform root, or a card id from the roots table), with what is within depth hops of them." },
|
|
374
|
+
changed: { type: "string", description: "A revision range, <base>..<head> or <base>...<head> (from the merge base): cut to what changed between the two commits and the cards within depth hops." },
|
|
375
|
+
depth: { type: "integer", description: "Hops from the cards around names, or from what changed (default 1).", minimum: 0, maximum: 10 },
|
|
376
|
+
direction: { type: "string", description: "With around: up follows what the cards depend on, down what depends on them (default both).", enum: ["up", "down"] }
|
|
377
|
+
};
|
|
378
|
+
function graphRequest(a, ctx) {
|
|
379
|
+
const dir = realDir(resolve(ctx.projectDir, typeof a.dir === "string" && a.dir ? a.dir : "."));
|
|
380
|
+
if (!within(ctx.projectDir, dir)) throw new ToolError(`dir ${String(a.dir)} is outside the project ${ctx.projectDir}; graph reads folders inside it`, { code: "outside-project" });
|
|
381
|
+
if (!existsSync2(dir) || !statSync(dir).isDirectory()) throw new ToolError(`dir ${String(a.dir)} is not a folder in the project`, { code: "not-a-directory" });
|
|
382
|
+
const around = typeof a.around === "string" ? a.around.split(",").map((x) => x.trim()).filter(Boolean) : void 0;
|
|
383
|
+
if (typeof a.around === "string" && !around?.length) throw new ToolError("around is empty: give one or more ids, comma separated");
|
|
384
|
+
const rel = relative(ctx.projectDir, dir).split(sep).join("/") || ".";
|
|
385
|
+
return {
|
|
386
|
+
rel,
|
|
387
|
+
req: {
|
|
388
|
+
dir,
|
|
389
|
+
...around ? { around } : {},
|
|
390
|
+
...typeof a.changed === "string" && a.changed ? { changed: a.changed } : {},
|
|
391
|
+
...a.depth !== void 0 ? { depth: a.depth } : {},
|
|
392
|
+
...a.direction === "up" || a.direction === "down" ? { direction: a.direction } : {}
|
|
393
|
+
}
|
|
394
|
+
};
|
|
395
|
+
}
|
|
396
|
+
async function readCut(ctx, req) {
|
|
397
|
+
try {
|
|
398
|
+
return await (ctx.readGraphCut ?? ((r) => readGraphCut(r, version())))(req);
|
|
399
|
+
} catch (e) {
|
|
400
|
+
if (e instanceof GraphToolError) throw new ToolError(e.message, e.body);
|
|
401
|
+
throw e;
|
|
402
|
+
}
|
|
403
|
+
}
|
|
404
|
+
var TOOLS = [
|
|
405
|
+
{
|
|
406
|
+
name: "ask",
|
|
407
|
+
description: `Ask a chant search query of the estate behold serves, and get chant's answer: its read-contract search document, verbatim, with \`link\` (the behold view that draws it) and \`drawn: false\` added. ask never moves the person's tab; use show for that. On a declared workspace the document is chant workspace search's, with every member's rows as <member>/<id>; on one project or a Terraform folder it is chant search --json's. Uses the running behold serve of this project; with none, behold answers in this process. Needs chant 0.124.46 or newer. Which demo questions it answers: "what's in here?" is countBy kind with the query kind:aws_ (or empty); "how many resources does each module own, by type?" is countBy module, then countBy kind with the query narrowed to a module; "what would this change do, and why does it replace the database?" is plan with the query attr:planAction=replace and show planActions,planReplacePaths,planActionReason. Beside a chant search query, ask takes cypher (a read-only Cypher query over every member's graph and every index in one LadybugDB, behold#1027) or resource (resolve a name, id, address or cloud id, then a template). ` + SEARCH_OPTIONS,
|
|
408
|
+
inputSchema: {
|
|
409
|
+
type: "object",
|
|
410
|
+
properties: {
|
|
411
|
+
query: VIEW_PROPS.query,
|
|
412
|
+
env: VIEW_PROPS.env,
|
|
413
|
+
snapshot: VIEW_PROPS.snapshot,
|
|
414
|
+
plan: VIEW_PROPS.plan,
|
|
415
|
+
countBy: VIEW_PROPS.countBy,
|
|
416
|
+
show: { type: "string", description: "Comma-separated attributes to carry on each row (chant search --show)." },
|
|
417
|
+
cypher: { type: "string", description: CYPHER_HELP },
|
|
418
|
+
params: { type: "string", description: 'With cypher: its parameters, as a JSON object ({"k": "aws_s3_bucket"} for $k). Values are strings, numbers, booleans or null.' },
|
|
419
|
+
resource: {
|
|
420
|
+
type: "string",
|
|
421
|
+
description: "Start from a resource (behold#1022): a name, an IR id, a block address or a cloud id (an ARN, an instance id, a Kubernetes UID). The answer is one node or the candidates, with the investigation templates that apply to it. Works without the LadybugDB peer."
|
|
422
|
+
},
|
|
423
|
+
template: { type: "string", description: "With resource that resolves to one node: run that template (dependents, dependencies, paths-to-kind, capability, drift, dependents-all, dependencies-all, ownership, same-object, readers, history)." },
|
|
424
|
+
inputs: { type: "string", description: 'With template: its inputs as a JSON object of strings ({"kind": "aws_internet_gateway"}).' }
|
|
425
|
+
},
|
|
426
|
+
additionalProperties: false
|
|
427
|
+
},
|
|
428
|
+
annotations: READ_ONLY,
|
|
429
|
+
async run(a, ctx) {
|
|
430
|
+
if (typeof a.cypher === "string" || typeof a.resource === "string") return askGraph(a, ctx);
|
|
431
|
+
if (a.params !== void 0 || a.template !== void 0 || a.inputs !== void 0) throw new ToolError("params goes with cypher, and template and inputs with resource");
|
|
432
|
+
const view = viewOf(a);
|
|
433
|
+
if (!view.q && !view.countBy) throw new ToolError("ask needs a query, or countBy to count the whole estate");
|
|
434
|
+
const q = new URLSearchParams({
|
|
435
|
+
q: view.q ?? "",
|
|
436
|
+
...view.env ? { env: view.env } : {},
|
|
437
|
+
...view.snapshot ? { snapshot: view.snapshot } : {},
|
|
438
|
+
...view.plan ? { plan: "1" } : {},
|
|
439
|
+
...view.countBy ? { countBy: view.countBy } : {},
|
|
440
|
+
...typeof a.show === "string" && a.show ? { show: a.show } : {}
|
|
441
|
+
});
|
|
442
|
+
const serve = await ctx.findServe();
|
|
443
|
+
let status;
|
|
444
|
+
let body;
|
|
445
|
+
if (serve?.ours) {
|
|
446
|
+
const res = await ctx.fetch(`${serve.url}/api/search?${q}`, { headers: { accept: "application/json" } });
|
|
447
|
+
status = res.status;
|
|
448
|
+
body = await res.json().catch(() => ({}));
|
|
449
|
+
} else {
|
|
450
|
+
({ status, body } = await ctx.localSearch(q));
|
|
451
|
+
}
|
|
452
|
+
const { doc, failed: refused } = askAnswer(status, body);
|
|
453
|
+
const note = serve?.ours ? `Nothing is drawn: ask never moves the tab. show with the same query draws it in the open tab at ${serve.url}.` : `Nothing is drawn: no behold serve of ${ctx.projectDir} was running${serve ? ` (the one at ${serve.url} serves ${serve.serves})` : ""}, so behold answered in this process. Start \`${serveCommand(ctx.projectDir)}\` to see it.`;
|
|
454
|
+
return { ...refused ? { isError: true } : {}, content: [{ type: "text", text: JSON.stringify(doc) }, { type: "text", text: note }] };
|
|
455
|
+
}
|
|
456
|
+
},
|
|
457
|
+
{
|
|
458
|
+
name: "show",
|
|
459
|
+
description: "Move the person's open behold tab to a view: the query's matches lit and the rest dimmed, in the env or snapshot asked for. The tab says an agent moved it and keeps the view it left one Back away. It changes nothing but what the tab shows. Needs a running behold serve of this project; with none, it refuses and names the command that starts one. With no tab open it answers the link to hand the person. " + SEARCH_OPTIONS,
|
|
460
|
+
inputSchema: { type: "object", properties: VIEW_PROPS, additionalProperties: false },
|
|
461
|
+
annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false },
|
|
462
|
+
async run(a, ctx) {
|
|
463
|
+
const view = viewOf(a);
|
|
464
|
+
if (!Object.keys(view).length) throw new ToolError("show needs a query or a view key (env, plan, countBy, member, zoom, focus, node)");
|
|
465
|
+
const serve = await ctx.findServe();
|
|
466
|
+
if (!serve) {
|
|
467
|
+
throw new ToolError(`No behold serve of ${ctx.projectDir} is running, so there is no tab to move. Start one with \`${serveCommand(ctx.projectDir)}\` and open it, or take a shot instead.`, {
|
|
468
|
+
code: "no-serve",
|
|
469
|
+
remedy: serveCommand(ctx.projectDir)
|
|
470
|
+
});
|
|
471
|
+
}
|
|
472
|
+
if (!serve.ours) {
|
|
473
|
+
throw new ToolError(`The behold at ${serve.url} serves ${serve.serves}, not ${ctx.projectDir}, so show won't move its tab.`, {
|
|
474
|
+
code: "other-project",
|
|
475
|
+
serves: serve.serves,
|
|
476
|
+
project: ctx.projectDir,
|
|
477
|
+
remedy: `Start behold for this project (\`${serveCommand(ctx.projectDir)} --port <n>\`) and pass behold mcp --url, or switch the open serve to it.`
|
|
478
|
+
});
|
|
479
|
+
}
|
|
480
|
+
const client = ctx.clientName();
|
|
481
|
+
const by = `${client ?? "an agent"} via behold mcp`.slice(0, 80);
|
|
482
|
+
const res = await ctx.fetch(`${serve.url}/api/view`, {
|
|
483
|
+
method: "POST",
|
|
484
|
+
headers: { "content-type": "application/json", accept: "application/json" },
|
|
485
|
+
// POST /api/view takes plan as a boolean, as a host's behold:view does.
|
|
486
|
+
body: JSON.stringify({ view: { ...view, ...view.plan ? { plan: true } : {} }, by })
|
|
487
|
+
});
|
|
488
|
+
const body = await res.json().catch(() => ({}));
|
|
489
|
+
if (!res.ok) throw new ToolError(typeof body.error === "string" ? body.error : `POST /api/view answered ${res.status}`, { status: res.status, ...body });
|
|
490
|
+
return json({ ...body, serve: serve.url });
|
|
491
|
+
}
|
|
492
|
+
},
|
|
493
|
+
{
|
|
494
|
+
name: "shot",
|
|
495
|
+
description: "A PNG of a view, framed on the query's matches, and the link to the same view. Returns the image inline. Uses the running behold serve of this project; with none, it starts behold in this process for the shot and stops it after. Needs the optional peer playwright-core and a browser; without them it refuses with the install line. Writes no file. Without a query, node or focus frames the view's own selection. " + SEARCH_OPTIONS,
|
|
496
|
+
inputSchema: {
|
|
497
|
+
type: "object",
|
|
498
|
+
properties: {
|
|
499
|
+
...VIEW_PROPS,
|
|
500
|
+
width: { type: "integer", description: "The page's width in px (default 1600).", minimum: 320, maximum: 4096 },
|
|
501
|
+
height: { type: "integer", description: "The page's height in px (default 1000).", minimum: 320, maximum: 4096 }
|
|
502
|
+
},
|
|
503
|
+
additionalProperties: false
|
|
504
|
+
},
|
|
505
|
+
annotations: READ_ONLY,
|
|
506
|
+
async run(a, ctx) {
|
|
507
|
+
const view = viewOf(a);
|
|
508
|
+
const serve = await ctx.findServe();
|
|
509
|
+
if (serve?.ours) {
|
|
510
|
+
const q2 = new URLSearchParams(view);
|
|
511
|
+
if (a.width !== void 0) q2.set("width", String(a.width));
|
|
512
|
+
if (a.height !== void 0) q2.set("height", String(a.height));
|
|
513
|
+
const res = await ctx.fetch(`${serve.url}/api/shot?${q2}`, { headers: { accept: "image/png" } });
|
|
514
|
+
if (!res.ok) {
|
|
515
|
+
const body = await res.json().catch(() => ({}));
|
|
516
|
+
throw new ToolError(typeof body.error === "string" ? body.error : `GET /api/shot answered ${res.status}`, { status: res.status, ...body });
|
|
517
|
+
}
|
|
518
|
+
const png = Buffer.from(await res.arrayBuffer());
|
|
519
|
+
const facts2 = { link: res.headers.get("behold-view-link"), state: res.headers.get("behold-shot-state"), serve: serve.url };
|
|
520
|
+
return { content: [{ type: "image", data: png.toString("base64"), mimeType: "image/png" }, { type: "text", text: JSON.stringify(facts2, null, 2) }] };
|
|
521
|
+
}
|
|
522
|
+
const { q, env, snapshot, ...rest } = view;
|
|
523
|
+
const req = {
|
|
524
|
+
...q ? { query: q } : {},
|
|
525
|
+
...env ? { env } : {},
|
|
526
|
+
...snapshot ? { snapshot } : {},
|
|
527
|
+
view: rest,
|
|
528
|
+
...a.width !== void 0 ? { width: a.width } : {},
|
|
529
|
+
...a.height !== void 0 ? { height: a.height } : {}
|
|
530
|
+
};
|
|
531
|
+
const shot = await ctx.localShot(req);
|
|
532
|
+
const facts = {
|
|
533
|
+
link: shot.link,
|
|
534
|
+
state: shot.state,
|
|
535
|
+
matched: shot.matched,
|
|
536
|
+
serve: null,
|
|
537
|
+
note: `No behold serve of ${ctx.projectDir} was running${serve ? ` (the one at ${serve.url} serves ${serve.serves})` : ""}, so behold ran in this process for the shot. The link opens once \`${serveCommand(ctx.projectDir)}\` is running.`
|
|
538
|
+
};
|
|
539
|
+
return { content: [{ type: "image", data: shot.png.toString("base64"), mimeType: "image/png" }, { type: "text", text: JSON.stringify(facts, null, 2) }] };
|
|
540
|
+
}
|
|
541
|
+
},
|
|
542
|
+
{
|
|
543
|
+
name: "capabilities",
|
|
544
|
+
description: "Read this first. The capability catalog chant answers cap: terms with, for the estate behold serves: chant's read-contract capabilities document, verbatim (chant search --capabilities --json, INTENTIUS/chant#4375; chant workspace search --capabilities --json on a declared workspace). Each capability has its name, what it means, its parameters, the search term that asks it (cap:internet-reachable, ->[cap=network]), the questions it answers, what it does not evaluate, its rule, and which lexicons supply it. Then ask with that term; a cap: match's path is in its because hops, and show draws it. Uses the running behold serve of this project; with none, behold answers in this process. Takes no arguments. Needs chant 0.124.46 or newer.",
|
|
545
|
+
inputSchema: { type: "object", properties: {}, additionalProperties: false },
|
|
546
|
+
annotations: READ_ONLY,
|
|
547
|
+
async run(_a, ctx) {
|
|
548
|
+
const serve = await ctx.findServe();
|
|
549
|
+
let status;
|
|
550
|
+
let text;
|
|
551
|
+
if (serve?.ours) {
|
|
552
|
+
const res = await ctx.fetch(`${serve.url}/api/capabilities`, { headers: { accept: "application/json" } });
|
|
553
|
+
status = res.status;
|
|
554
|
+
text = await res.text();
|
|
555
|
+
} else {
|
|
556
|
+
({ status, text } = await ctx.localCapabilities());
|
|
557
|
+
}
|
|
558
|
+
let body = {};
|
|
559
|
+
try {
|
|
560
|
+
const parsed = JSON.parse(text);
|
|
561
|
+
if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) body = parsed;
|
|
562
|
+
} catch {
|
|
563
|
+
}
|
|
564
|
+
if (body.contract === void 0) throw new ToolError(typeof body.error === "string" ? body.error : `GET /api/capabilities answered ${status}`, { status, ...body });
|
|
565
|
+
return { ..."error" in body || status !== 200 ? { isError: true } : {}, content: [{ type: "text", text }] };
|
|
566
|
+
}
|
|
567
|
+
},
|
|
568
|
+
{
|
|
569
|
+
name: "graph",
|
|
570
|
+
description: "Draw the repository as a graph, or a cut of it. A host that renders MCP Apps shows the interactive view inline; every other host gets this answer: how many roots, cards and edges, the cut asked for, a Mermaid diagram when it fits (else a table of roots with card counts), and a link to the running behold serve at that view. The answer holds no document JSON, and no card list when the diagram does not fit. For a big estate ask again with around, a root or card id from the table, to see one part. Reads the files and git objects in this process; it needs no serve and no chant search. dir is a folder inside the project (default: the project). around takes comma-separated card or box ids and cuts to them and what is within depth hops (default 1); direction up follows what they depend on, down what depends on them. changed takes <base>..<head> (or <base>...<head> from the merge base) and cuts to what changed between the two commits, each card marked added, removed, changed or neighbour. around and changed are two cuts: give one.",
|
|
571
|
+
inputSchema: { type: "object", properties: GRAPH_PROPS, additionalProperties: false },
|
|
572
|
+
annotations: READ_ONLY,
|
|
573
|
+
// The flat key is the form hosts read before MCP Apps settled on `ui.resourceUri`; both name the same view.
|
|
574
|
+
_meta: { ui: { resourceUri: VIEWER_URI }, "ui/resourceUri": VIEWER_URI },
|
|
575
|
+
async run(a, ctx) {
|
|
576
|
+
const { rel, req } = graphRequest(a, ctx);
|
|
577
|
+
const read = await readCut(ctx, req);
|
|
578
|
+
const serve = await ctx.findServe();
|
|
579
|
+
const q = new URLSearchParams(viewQuery(req, read.document)).toString();
|
|
580
|
+
const base = serve?.ours ? serve.url : DEFAULT_LINK_BASE;
|
|
581
|
+
const link = { url: `${base}/${q ? `?${q}` : ""}`, serving: serve?.ours === true, command: serveCommand(ctx.projectDir) };
|
|
582
|
+
const text = graphText({ dir: rel, request: req, read, link });
|
|
583
|
+
const view = { dir: rel, ...req.around ? { around: req.around.join(",") } : {}, ...req.changed ? { changed: req.changed } : {}, ...req.depth !== void 0 ? { depth: req.depth } : {}, ...req.direction ? { direction: req.direction } : {} };
|
|
584
|
+
return {
|
|
585
|
+
content: [{ type: "text", text }],
|
|
586
|
+
structuredContent: { view, roots: read.whole.roots, cards: read.document.nodes.length, edges: read.document.edges.length, wholeCards: read.whole.cards, wholeEdges: read.whole.edges, link: link.url }
|
|
587
|
+
};
|
|
588
|
+
}
|
|
589
|
+
},
|
|
590
|
+
{
|
|
591
|
+
name: "graph_document",
|
|
592
|
+
description: "For the graph view only, not for a model: the behold-graph/1 document of a graph call, taking the same arguments, so the view can draw it. The model is never offered this tool, and its answer never enters the conversation.",
|
|
593
|
+
inputSchema: { type: "object", properties: GRAPH_PROPS, additionalProperties: false },
|
|
594
|
+
annotations: READ_ONLY,
|
|
595
|
+
_meta: { ui: { visibility: ["app"] } },
|
|
596
|
+
async run(a, ctx) {
|
|
597
|
+
const { req } = graphRequest(a, ctx);
|
|
598
|
+
const read = await readCut(ctx, req);
|
|
599
|
+
return {
|
|
600
|
+
content: [{ type: "text", text: `behold-graph/1 document for the view: ${read.document.nodes.length} cards, ${read.document.edges.length} edges.` }],
|
|
601
|
+
structuredContent: { document: read.document }
|
|
602
|
+
};
|
|
603
|
+
}
|
|
604
|
+
}
|
|
605
|
+
];
|
|
606
|
+
async function callTool(tools, name, args, ctx) {
|
|
607
|
+
const tool = tools.find((t) => t.name === name);
|
|
608
|
+
if (!tool) return failed(refusal(name));
|
|
609
|
+
try {
|
|
610
|
+
return await tool.run(checkArgs(tool, args), ctx);
|
|
611
|
+
} catch (e) {
|
|
612
|
+
if (e instanceof ToolError) return failed(e.message, e.body);
|
|
613
|
+
const body = e.body;
|
|
614
|
+
if (body?.code) return failed(body.error, { code: body.code, remedy: body.remedy });
|
|
615
|
+
return failed(`${name} failed: ${e.message}`);
|
|
616
|
+
}
|
|
617
|
+
}
|
|
618
|
+
function version() {
|
|
619
|
+
try {
|
|
620
|
+
const here = dirname2(fileURLToPath2(import.meta.url));
|
|
621
|
+
return JSON.parse(readFileSync2(join2(here, "..", "package.json"), "utf8")).version ?? "unknown";
|
|
622
|
+
} catch {
|
|
623
|
+
return "unknown";
|
|
624
|
+
}
|
|
625
|
+
}
|
|
626
|
+
var INSTRUCTIONS = "behold draws a Terraform or chant estate in the person's browser. Read capabilities first: chant's capability catalog, what each cap: term means and asks. ask returns chant's answer to an estate question (its search document, verbatim, plus the link to the view); then use show to move the person's open behold tab to the matches, or shot to get a PNG of them and the link. graph draws the repository, or a cut of it (around a root or card, or what changed between two commits): an interactive view in a host that renders MCP Apps, and a summary, a Mermaid diagram or a table of roots, and a link in every other. Nothing here deploys, approves, runs an Op, rolls back or writes; a person does that.";
|
|
627
|
+
async function serveMcp(o, transport) {
|
|
628
|
+
const tools = o.tools ?? TOOLS;
|
|
629
|
+
assertNoWrites(tools);
|
|
630
|
+
const projectDir = realDir(o.projectDir);
|
|
631
|
+
const fetch = o.fetch ?? ((url, init) => globalThis.fetch(url, init));
|
|
632
|
+
const server = new Server({ name: "behold", version: version() }, { capabilities: { tools: {}, resources: {} }, instructions: INSTRUCTIONS });
|
|
633
|
+
const ctx = {
|
|
634
|
+
projectDir,
|
|
635
|
+
projectGiven: o.projectGiven ?? true,
|
|
636
|
+
...o.url ? { url: o.url } : {},
|
|
637
|
+
fetch,
|
|
638
|
+
clientName: () => server.getClientVersion()?.name,
|
|
639
|
+
findServe: () => locateServe({ projectDir, projectGiven: o.projectGiven ?? true, ...o.url ? { url: o.url } : {}, fetch, ...o.registry ? { registry: o.registry } : {} }),
|
|
640
|
+
localShot: o.localShot ?? ((req) => shotFromArgs({ req, projectDir, linkBase: DEFAULT_LINK_BASE })),
|
|
641
|
+
localSearch: o.localSearch ?? ((query) => localSearch(projectDir, query)),
|
|
642
|
+
localCapabilities: o.localCapabilities ?? (() => localCapabilities(projectDir)),
|
|
643
|
+
...o.readGraphCut ? { readGraphCut: o.readGraphCut } : {}
|
|
644
|
+
};
|
|
645
|
+
server.setRequestHandler(ListToolsRequestSchema, async () => ({
|
|
646
|
+
tools: tools.map((t) => ({ name: t.name, description: t.description, inputSchema: t.inputSchema, annotations: t.annotations, ...t._meta ? { _meta: t._meta } : {} }))
|
|
647
|
+
}));
|
|
648
|
+
server.setRequestHandler(ListResourcesRequestSchema, async () => ({
|
|
649
|
+
resources: [{ uri: VIEWER_URI, name: "behold graph viewer", description: "The interactive graph view the graph tool draws in a host that renders MCP Apps.", mimeType: APP_MIME }]
|
|
650
|
+
}));
|
|
651
|
+
server.setRequestHandler(ReadResourceRequestSchema, async (req) => {
|
|
652
|
+
if (req.params.uri !== VIEWER_URI) throw new Error(`there is no resource ${req.params.uri}; behold serves ${VIEWER_URI}`);
|
|
653
|
+
return { contents: [{ uri: VIEWER_URI, mimeType: APP_MIME, text: (o.viewer ?? loadViewer()).html }] };
|
|
654
|
+
});
|
|
655
|
+
server.setRequestHandler(CallToolRequestSchema, async (req) => callTool(tools, req.params.name, req.params.arguments, ctx));
|
|
656
|
+
await server.connect(transport);
|
|
657
|
+
return server;
|
|
658
|
+
}
|
|
659
|
+
var MCP_USAGE = `Usage: behold mcp [project-dir] [--url <serve> | --port <n>]
|
|
660
|
+
|
|
661
|
+
A stdio MCP server with five tools: capabilities returns chant's
|
|
662
|
+
capability catalog, verbatim, to read first; ask returns chant's search
|
|
663
|
+
document for a query, verbatim, with the link to the view that draws it;
|
|
664
|
+
show moves the open behold tab to a view; shot returns a PNG of one with
|
|
665
|
+
its link; graph draws the repository, or a cut of it, as an interactive view
|
|
666
|
+
in a host that renders MCP Apps (the ui://behold/viewer resource) and as a
|
|
667
|
+
summary with a Mermaid diagram and a link in every other. A sixth tool,
|
|
668
|
+
graph_document, is for the view only and is hidden from the model.
|
|
669
|
+
ask also takes cypher, a read-only Cypher query over the graph pane's
|
|
670
|
+
database (needs the optional peer @ladybugdb/core), or resource, a name,
|
|
671
|
+
id, address or cloud id to resolve, with a template to run on it.
|
|
672
|
+
chant answers and behold draws. Configure it in the agent,
|
|
673
|
+
for example: claude mcp add behold -- npx @intentius/behold mcp <dir>
|
|
674
|
+
|
|
675
|
+
It reaches the serve at --url (or http://127.0.0.1:--port), else the serve
|
|
676
|
+
of project-dir (default: the current directory) that the per-user registry
|
|
677
|
+
under the OS temp directory names, else http://127.0.0.1:4600. With no serve
|
|
678
|
+
running, show refuses with the command that starts one, and capabilities,
|
|
679
|
+
ask and shot start behold in their own process. Nothing it does deploys, approves,
|
|
680
|
+
runs an Op, rolls back or writes.
|
|
681
|
+
`;
|
|
682
|
+
function parseMcpArgs(rest, cwd = process.cwd()) {
|
|
683
|
+
let url;
|
|
684
|
+
let port;
|
|
685
|
+
const positional = [];
|
|
686
|
+
for (let i = 0; i < rest.length; i++) {
|
|
687
|
+
const a = rest[i];
|
|
688
|
+
if (a === "-h" || a === "--help") return "help";
|
|
689
|
+
else if (a === "--url") url = rest[++i];
|
|
690
|
+
else if (a === "--port") port = rest[++i];
|
|
691
|
+
else if (a.startsWith("-")) throw new Error(`unexpected argument '${a}'`);
|
|
692
|
+
else positional.push(a);
|
|
693
|
+
}
|
|
694
|
+
if (positional.length > 1) throw new Error(`unexpected argument '${positional[1]}'`);
|
|
695
|
+
if (url !== void 0 && port !== void 0) throw new Error("pass --url or --port, not both");
|
|
696
|
+
if (port !== void 0) {
|
|
697
|
+
const n = Number(port);
|
|
698
|
+
if (!Number.isInteger(n) || n < 1 || n > 65535) throw new Error(`--port needs a port number, not ${port ?? "nothing"}`);
|
|
699
|
+
url = `http://127.0.0.1:${n}`;
|
|
700
|
+
}
|
|
701
|
+
if (url !== void 0) {
|
|
702
|
+
let u;
|
|
703
|
+
try {
|
|
704
|
+
u = new URL(url);
|
|
705
|
+
} catch {
|
|
706
|
+
throw new Error(`--url is not an http(s) URL: ${url}`);
|
|
707
|
+
}
|
|
708
|
+
if (u.protocol !== "http:" && u.protocol !== "https:") throw new Error(`--url is not an http(s) URL: ${url}`);
|
|
709
|
+
}
|
|
710
|
+
return { projectDir: resolve(cwd, positional[0] ?? "."), projectGiven: positional.length > 0 || url === void 0, ...url ? { url } : {} };
|
|
711
|
+
}
|
|
712
|
+
async function runMcp(rest) {
|
|
713
|
+
let o;
|
|
714
|
+
try {
|
|
715
|
+
o = parseMcpArgs(rest);
|
|
716
|
+
} catch (e) {
|
|
717
|
+
process.stderr.write(`behold mcp: ${e.message}
|
|
718
|
+
|
|
719
|
+
${MCP_USAGE}`);
|
|
720
|
+
return 2;
|
|
721
|
+
}
|
|
722
|
+
if (o === "help") {
|
|
723
|
+
process.stdout.write(MCP_USAGE);
|
|
724
|
+
return 0;
|
|
725
|
+
}
|
|
726
|
+
const server = await serveMcp(o, new StdioServerTransport());
|
|
727
|
+
await new Promise((resolve2) => {
|
|
728
|
+
server.onclose = () => resolve2();
|
|
729
|
+
process.stdin.once("end", () => resolve2());
|
|
730
|
+
process.stdin.once("close", () => resolve2());
|
|
731
|
+
});
|
|
732
|
+
await server.close();
|
|
733
|
+
return 0;
|
|
734
|
+
}
|
|
735
|
+
export {
|
|
736
|
+
DEFAULT_SERVE_URL,
|
|
737
|
+
INSTRUCTIONS,
|
|
738
|
+
MCP_USAGE,
|
|
739
|
+
TOOLS,
|
|
740
|
+
ToolError,
|
|
741
|
+
WRITE_WORDS,
|
|
742
|
+
askAnswer,
|
|
743
|
+
assertNoWrites,
|
|
744
|
+
callTool,
|
|
745
|
+
checkArgs,
|
|
746
|
+
locateServe,
|
|
747
|
+
parseMcpArgs,
|
|
748
|
+
refusal,
|
|
749
|
+
runMcp,
|
|
750
|
+
serveCommand,
|
|
751
|
+
serveMcp,
|
|
752
|
+
writeWord
|
|
753
|
+
};
|