@hippo-digital/hippocampus 2.2.0 → 2.3.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/CHANGELOG.md +46 -0
- package/README.md +25 -0
- package/bin/hippocampus.js +1 -0
- package/lib/brief.js +115 -0
- package/lib/mcp-server.js +193 -0
- package/package.json +10 -2
- package/scripts/mcp.js +86 -0
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,51 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 2.3.0
|
|
4
|
+
|
|
5
|
+
`hippocampus mcp` serves the knowledge base to agents over MCP, read-only, so an
|
|
6
|
+
agent building or reviewing a journey can ask what is already known instead of
|
|
7
|
+
being handed a copy of it. Ported from Ed Hiley's Design Brain server in the NAER
|
|
8
|
+
prototype, with the tool names kept so agents already written against it work
|
|
9
|
+
unchanged.
|
|
10
|
+
|
|
11
|
+
```bash
|
|
12
|
+
npx hippocampus mcp # HTTP on http://127.0.0.1:3100/mcp
|
|
13
|
+
npx hippocampus mcp --stdio # for a client that starts the server itself
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
Six tools, all `design_brain_*`:
|
|
17
|
+
|
|
18
|
+
- **`design_brain_brief`** - start here. Give it a role, scenario, journey or
|
|
19
|
+
build spec and it returns one brief: the needs, scenarios with their edge
|
|
20
|
+
cases, journey steps, build-spec acceptance criteria, screens, decisions,
|
|
21
|
+
insights and design actions, each with its record id. Assumptions are kept in
|
|
22
|
+
their own section as beliefs, not research. A subject that matches nothing
|
|
23
|
+
says so rather than returning everything.
|
|
24
|
+
- **`design_brain_known`** - `hippocampus known` on a topic.
|
|
25
|
+
- **`design_brain_consequences`** - `hippocampus consequences` on a scenario id.
|
|
26
|
+
New; the NAER server did not have it.
|
|
27
|
+
- **`design_brain_overview`** - record counts, scenario ids, build specs and the
|
|
28
|
+
skills this package ships.
|
|
29
|
+
- **`design_brain_read`** - a file or folder in the project.
|
|
30
|
+
- **`design_brain_ask`** - a free question, answered by a Gemini model that
|
|
31
|
+
calls the tools above. Optional: it needs `GEMINI_API_KEY`,
|
|
32
|
+
`DESIGN_BRAIN_MODEL` and `@google/genai` installed in the host (an optional
|
|
33
|
+
peer), and says it is off when any of them is missing. Every other tool runs
|
|
34
|
+
without a model.
|
|
35
|
+
|
|
36
|
+
`known` and `consequences` answer through the package's own commands, so the
|
|
37
|
+
MCP answer and the terminal answer are the same answer.
|
|
38
|
+
|
|
39
|
+
It binds to 127.0.0.1 only. `DESIGN_BRAIN_MCP_PORT` changes the port and
|
|
40
|
+
`DESIGN_BRAIN_MCP_LOG=<file>` appends each call and its answer to a file.
|
|
41
|
+
|
|
42
|
+
`design_brain_read` is confined to the project root, and refuses `.env*`,
|
|
43
|
+
`.git`, `.npmrc` and `node_modules` anywhere in the path. The NAER version would
|
|
44
|
+
serve `.env`, which is where `GEMINI_API_KEY` lives.
|
|
45
|
+
|
|
46
|
+
`@modelcontextprotocol/sdk` is a new dependency. The install gate now checks
|
|
47
|
+
that `hippocampus mcp` loads in a real install.
|
|
48
|
+
|
|
3
49
|
## 2.2.0
|
|
4
50
|
|
|
5
51
|
`hippocampus consequences <scenario-id>` runs a new or changed journey against the
|
package/README.md
CHANGED
|
@@ -140,6 +140,7 @@ npx hippocampus validate # parse, check integrity, report coverage ga
|
|
|
140
140
|
npx hippocampus validate --strict # and fail on warnings
|
|
141
141
|
npx hippocampus known "topic" # what is already known, what was built on it, what nobody asked
|
|
142
142
|
npx hippocampus consequences <id> # run a new journey against the users we already know
|
|
143
|
+
npx hippocampus mcp # serve the knowledge base to agents over MCP
|
|
143
144
|
npx hippocampus research triage # rank a research folder before importing anything
|
|
144
145
|
npx hippocampus research sync # inbox artefacts to reviewable drafts
|
|
145
146
|
npx hippocampus source index # record what was ingested, before the copies go
|
|
@@ -157,6 +158,30 @@ hippocampus: knowledge data is valid
|
|
|
157
158
|
info 108 of 132 needs (82%) sit at priority "medium"
|
|
158
159
|
```
|
|
159
160
|
|
|
161
|
+
## Serving it to agents over MCP
|
|
162
|
+
|
|
163
|
+
```bash
|
|
164
|
+
npx hippocampus mcp # HTTP on http://127.0.0.1:3100/mcp
|
|
165
|
+
npx hippocampus mcp --stdio # for a client that starts the server itself
|
|
166
|
+
```
|
|
167
|
+
|
|
168
|
+
Read-only, localhost only. The tools are `design_brain_brief` (start here: one
|
|
169
|
+
brief for a role, scenario, journey or build spec, with record ids),
|
|
170
|
+
`design_brain_known`, `design_brain_consequences`, `design_brain_overview`,
|
|
171
|
+
`design_brain_read` and `design_brain_ask`. Only `ask` uses a model; it needs
|
|
172
|
+
`GEMINI_API_KEY`, `DESIGN_BRAIN_MODEL` and `npm install @google/genai`, and
|
|
173
|
+
reports that it is off otherwise.
|
|
174
|
+
|
|
175
|
+
To add it to Claude Code:
|
|
176
|
+
|
|
177
|
+
```bash
|
|
178
|
+
claude mcp add --transport http design_brain http://127.0.0.1:3100/mcp
|
|
179
|
+
```
|
|
180
|
+
|
|
181
|
+
`DESIGN_BRAIN_MCP_PORT` changes the port. `DESIGN_BRAIN_MCP_LOG=<file>` logs
|
|
182
|
+
each call. `design_brain_read` never serves `.env`, `.git`, `.npmrc` or
|
|
183
|
+
`node_modules`.
|
|
184
|
+
|
|
160
185
|
## Documentation
|
|
161
186
|
|
|
162
187
|
The guides are served by the viewer at `{basePath}/docs`, so they always
|
package/bin/hippocampus.js
CHANGED
|
@@ -19,6 +19,7 @@ const COMMANDS = {
|
|
|
19
19
|
validate: 'validate-knowledge.js',
|
|
20
20
|
known: 'known.js',
|
|
21
21
|
consequences: 'consequences.js',
|
|
22
|
+
mcp: 'mcp.js',
|
|
22
23
|
migrate: 'migrate-knowledge.js',
|
|
23
24
|
'research sync': 'sync-research-artefacts.js',
|
|
24
25
|
'research triage': 'triage-research-corpus.js',
|
package/lib/brief.js
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
const fs = require('fs')
|
|
2
|
+
const path = require('path')
|
|
3
|
+
|
|
4
|
+
// "Tell me everything you know about the paramedic" answered in one read.
|
|
5
|
+
//
|
|
6
|
+
// An agent building a feature needs the user's needs, the scenarios and journey
|
|
7
|
+
// steps, the build spec, the screens, and the decisions, assumptions and
|
|
8
|
+
// insights that surround them - each with its record id, so what it writes can
|
|
9
|
+
// cite the knowledge base rather than paraphrase it. Keyword search alone finds
|
|
10
|
+
// the words and misses the structure: the first agents to use this knowledge
|
|
11
|
+
// base over MCP ran one `known` query and missed contested items, the build
|
|
12
|
+
// spec and every record id.
|
|
13
|
+
//
|
|
14
|
+
// So a brief starts from the user roles the subject names, because a role links
|
|
15
|
+
// most of the graph, takes the scenarios, journeys, needs and screens around
|
|
16
|
+
// it, then follows the relationships one step out for decisions, assumptions,
|
|
17
|
+
// insights and design actions. Assumptions stay labelled as beliefs.
|
|
18
|
+
//
|
|
19
|
+
// Ported from the Design Brain MCP server Ed Hiley wrote for NAER.
|
|
20
|
+
|
|
21
|
+
const MAX_CHARS = 40000
|
|
22
|
+
|
|
23
|
+
function readBuildSpecs (root) {
|
|
24
|
+
const dir = path.join(root, 'build-specs')
|
|
25
|
+
if (!fs.existsSync(dir)) return []
|
|
26
|
+
return fs.readdirSync(dir)
|
|
27
|
+
.filter((f) => f.endsWith('.json') && !f.startsWith('_'))
|
|
28
|
+
.map((f) => {
|
|
29
|
+
try {
|
|
30
|
+
return { file: `build-specs/${f}`, ...JSON.parse(fs.readFileSync(path.join(dir, f), 'utf8')) }
|
|
31
|
+
} catch (error) {
|
|
32
|
+
return { file: `build-specs/${f}`, error: error.message }
|
|
33
|
+
}
|
|
34
|
+
})
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function brief (knowledge, subject, { buildSpecs = [], maxChars = MAX_CHARS } = {}) {
|
|
38
|
+
const text = String(subject || '').trim()
|
|
39
|
+
const tokens = text.toLowerCase().split(/[^a-z0-9]+/).filter((t) => t.length > 2)
|
|
40
|
+
const slug = tokens.join('-')
|
|
41
|
+
const matches = (value) => tokens.some((t) => String(value ?? '').toLowerCase().includes(t))
|
|
42
|
+
const list = (key) => knowledge[key] || []
|
|
43
|
+
|
|
44
|
+
// Start from the user roles the subject names. A role links most of the knowledge base.
|
|
45
|
+
const users = list('users').filter((u) =>
|
|
46
|
+
tokens.includes(u.id) || tokens.some((t) => u.id.split('-').includes(t)) || matches(u.label))
|
|
47
|
+
const userIds = new Set(users.map((u) => u.id))
|
|
48
|
+
|
|
49
|
+
const scenarios = list('scenarios').filter((s) => userIds.has(s.userId) || (slug && s.id.includes(slug)))
|
|
50
|
+
const scenarioIds = new Set(scenarios.map((s) => s.id))
|
|
51
|
+
const journeys = list('journeys').filter((j) => scenarioIds.has(j.scenarioId) || (slug && j.id.includes(slug)))
|
|
52
|
+
const needs = list('needs').filter((n) => userIds.has(n.userId) || scenarios.some((s) => (s.needIds || []).includes(n.id)))
|
|
53
|
+
const needIds = new Set(needs.map((n) => n.id))
|
|
54
|
+
const stepScreens = new Set(journeys.flatMap((j) => (j.steps || []).flatMap((s) => s.screenIds || [])))
|
|
55
|
+
const screens = list('screens').filter((s) => stepScreens.has(s.id) || (s.needIds || []).some((id) => needIds.has(id)))
|
|
56
|
+
const specs = buildSpecs.filter((b) => userIds.has(b.role?.id) || (slug && (b.journeySlug || '').includes(slug)))
|
|
57
|
+
|
|
58
|
+
// Follow the relationships one step out from the core records.
|
|
59
|
+
const core = new Set([...userIds, ...scenarioIds, ...journeys.map((j) => j.id), ...needIds, ...screens.map((s) => s.id)])
|
|
60
|
+
const linked = new Set()
|
|
61
|
+
for (const r of list('relationships')) {
|
|
62
|
+
if (core.has(r.from)) linked.add(r.to)
|
|
63
|
+
if (core.has(r.to)) linked.add(r.from)
|
|
64
|
+
}
|
|
65
|
+
for (const n of needs) for (const id of n.evidenceIds || []) linked.add(id)
|
|
66
|
+
for (const j of journeys) {
|
|
67
|
+
for (const s of j.steps || []) for (const id of [...(s.decisionIds || []), ...(s.evidenceIds || [])]) linked.add(id)
|
|
68
|
+
}
|
|
69
|
+
const pick = (items) => items.filter((i) => linked.has(i.id))
|
|
70
|
+
const decisions = pick(list('decisions'))
|
|
71
|
+
// Assumptions are often not linked in the graph, so also take any that name the role or cite its needs.
|
|
72
|
+
const assumptions = list('assumptions').filter((a) => linked.has(a.id) ||
|
|
73
|
+
(a.needIds || []).some((id) => needIds.has(id)) ||
|
|
74
|
+
users.some((u) => String(a.statement || '').toLowerCase().includes(String(u.label || '').toLowerCase())))
|
|
75
|
+
const insights = pick(list('insights'))
|
|
76
|
+
const actions = pick(list('designActions'))
|
|
77
|
+
const rounds = new Map(list('researchRounds').map((r) => [r.id, r]))
|
|
78
|
+
|
|
79
|
+
if (!users.length && !journeys.length && !scenarios.length && !specs.length) {
|
|
80
|
+
return `No user, scenario, journey or build spec matches "${text}". Use a keyword search (known) for a topic, or the overview to see what exists.`
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
const out = [`# Brief: ${text}`, 'Every item has its record ID. Cite these IDs. Assumptions are beliefs, not research.']
|
|
84
|
+
const section = (title, items, line) => {
|
|
85
|
+
if (!items.length) return
|
|
86
|
+
out.push(`\n## ${title} (${items.length})`)
|
|
87
|
+
for (const i of items) out.push(line(i))
|
|
88
|
+
}
|
|
89
|
+
const edge = (e) => (typeof e === 'string' ? e : e.label || e.title || JSON.stringify(e))
|
|
90
|
+
section('Users', users, (u) => `- ${u.id}: ${u.label}. ${u.description || ''}`.trim())
|
|
91
|
+
section('Needs', needs, (n) => `- ${n.id} [${n.priority}]: ${n.statement}`)
|
|
92
|
+
section('Scenarios', scenarios, (s) => `- ${s.id} [risk ${s.riskLevel}]: ${s.title}. Trigger: ${s.trigger || ''}` +
|
|
93
|
+
((s.edgeCases || []).length ? `\n Edge cases: ${s.edgeCases.map(edge).join('; ')}` : ''))
|
|
94
|
+
section('Journeys', journeys, (j) => [`- ${j.id}: ${j.title}. ${j.description || ''}`.trim(),
|
|
95
|
+
...(j.steps || []).map((s) => ` - ${s.id}: ${s.label}. ${s.userAction || ''}` +
|
|
96
|
+
((s.frontstage || []).length ? `\n Shows: ${s.frontstage.join('; ')}` : '') +
|
|
97
|
+
((s.exceptionHandling || []).length ? `\n Exceptions: ${s.exceptionHandling.join('; ')}` : '') +
|
|
98
|
+
((s.needIds || []).length ? `\n Needs: ${s.needIds.join(', ')}` : ''))].join('\n'))
|
|
99
|
+
section('Build specs', specs, (b) => [`- ${b.file} (journey ${b.journeySlug}, role ${b.role?.id}: "${b.role?.need || ''}")`,
|
|
100
|
+
...(b.acceptanceCriteria || []).map((a) => ` - Acceptance: ${a}`),
|
|
101
|
+
...(b.a11yRequirements || []).map((a) => ` - Accessibility: ${a}`),
|
|
102
|
+
...(b.routes || []).map((r) => ` - Route: ${r.method} ${r.path}. ${r.notes || ''}`.trim())].join('\n'))
|
|
103
|
+
section('Screens', screens, (s) => `- ${s.id} ${s.route}: ${s.title}. ${s.purpose || ''}`.trim())
|
|
104
|
+
section('Decisions', decisions, (d) => `- ${d.id} [${d.status}]: ${d.title}. ${d.decision || ''}`.trim())
|
|
105
|
+
section('Assumptions (beliefs, not research)', assumptions, (a) => `- ${a.id} [risk ${a.risk}]: ${a.statement}`)
|
|
106
|
+
section('Insights', insights, (i) => {
|
|
107
|
+
const round = rounds.get(i.roundId)
|
|
108
|
+
return `- ${i.id} [${i.confidence}, ${round?.title || i.roundId}, ${round?.date || ''}]: ${i.title}`
|
|
109
|
+
})
|
|
110
|
+
section('Design actions', actions, (a) => `- ${a.id} [${a.status}]: ${a.title}`)
|
|
111
|
+
const result = out.join('\n')
|
|
112
|
+
return result.length > maxChars ? `${result.slice(0, maxChars)}\n\n[Cut at ${maxChars} of ${result.length} characters.]` : result
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
module.exports = { brief, readBuildSpecs, MAX_CHARS }
|
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
const fs = require('fs')
|
|
2
|
+
const path = require('path')
|
|
3
|
+
const { spawnSync } = require('child_process')
|
|
4
|
+
const { z } = require('zod')
|
|
5
|
+
const packagePaths = require('./package-paths')
|
|
6
|
+
const { brief, readBuildSpecs, MAX_CHARS } = require('./brief')
|
|
7
|
+
|
|
8
|
+
// An MCP server that gives agents in other tools read-only access to a
|
|
9
|
+
// Hippocampus knowledge base - the "design brain" half of two brains and a join.
|
|
10
|
+
//
|
|
11
|
+
// Ed Hiley wrote the first version inside the NAER prototype, for Hippo Agents
|
|
12
|
+
// to read the design knowledge base while it builds. It lives here instead so
|
|
13
|
+
// every project that installs the package gets it, and so the tools answer from
|
|
14
|
+
// the package's own commands (known, consequences) rather than a copy of them.
|
|
15
|
+
//
|
|
16
|
+
// The tool names keep his `design_brain_` prefix: Hippo Agents' skills already
|
|
17
|
+
// look for `design_brain_*` tools, and a client should not have to change to
|
|
18
|
+
// move from the project's server to the package's.
|
|
19
|
+
//
|
|
20
|
+
// Read-only by construction: there is no tool that writes, and `read` refuses
|
|
21
|
+
// anything outside the project root and anything that looks like a secret.
|
|
22
|
+
|
|
23
|
+
const TOOL_PREFIX = 'design_brain_'
|
|
24
|
+
const SECRET = /(^|[\\/])(\.env[^\\/]*|\.git|\.npmrc|node_modules)([\\/]|$)/i
|
|
25
|
+
|
|
26
|
+
function clip (text) {
|
|
27
|
+
return text.length > MAX_CHARS ? `${text.slice(0, MAX_CHARS)}\n\n[Cut at ${MAX_CHARS} of ${text.length} characters.]` : text
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
// known and consequences answer through the package's own CLIs, so an agent
|
|
31
|
+
// gets exactly what a person running the command sees.
|
|
32
|
+
function runCommand (script, args, root) {
|
|
33
|
+
const result = spawnSync(process.execPath, [path.join(packagePaths.scriptsDir, script), ...args, '--root', root],
|
|
34
|
+
{ cwd: root, encoding: 'utf8', timeout: 120000 })
|
|
35
|
+
if (result.status !== 0) return `The command failed.\n${(result.stderr || result.stdout || '').slice(-2000)}`
|
|
36
|
+
return clip(result.stdout)
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function tree (dir, depth, prefix = '') {
|
|
40
|
+
const lines = []
|
|
41
|
+
for (const name of fs.readdirSync(dir).sort()) {
|
|
42
|
+
if (SECRET.test(name)) continue
|
|
43
|
+
const full = path.join(dir, name)
|
|
44
|
+
const isDir = fs.statSync(full).isDirectory()
|
|
45
|
+
lines.push(`${prefix}${name}${isDir ? '/' : ''}`)
|
|
46
|
+
if (isDir && depth > 1) lines.push(...tree(full, depth - 1, `${prefix} `))
|
|
47
|
+
}
|
|
48
|
+
return lines
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function createTools (ctx, { env = process.env } = {}) {
|
|
52
|
+
const root = ctx.root
|
|
53
|
+
const knowledge = () => ctx.requireProjects()[0].store.getKnowledge()
|
|
54
|
+
|
|
55
|
+
const tools = {
|
|
56
|
+
brief: (subject) => brief(knowledge(), subject, { buildSpecs: readBuildSpecs(root) }),
|
|
57
|
+
|
|
58
|
+
known: (topic) => runCommand('known.js', [topic], root),
|
|
59
|
+
|
|
60
|
+
consequences: (scenarioId) => runCommand('consequences.js', [scenarioId], root),
|
|
61
|
+
|
|
62
|
+
overview: () => {
|
|
63
|
+
const k = knowledge()
|
|
64
|
+
const lines = [
|
|
65
|
+
`Knowledge base root: ${root}`,
|
|
66
|
+
'All paths are inside this project, not the one you are building. Read them with design_brain_read.',
|
|
67
|
+
'Start with design_brain_brief for a user role, journey or feature. Use design_brain_known for a topic,',
|
|
68
|
+
'design_brain_consequences for a new or changed journey, and design_brain_ask for anything else.',
|
|
69
|
+
'',
|
|
70
|
+
'Knowledge base (record count):'
|
|
71
|
+
]
|
|
72
|
+
for (const [key, value] of Object.entries(k)) {
|
|
73
|
+
if (Array.isArray(value)) lines.push(`- ${key}: ${value.length}`)
|
|
74
|
+
}
|
|
75
|
+
const scenarios = k.scenarios || []
|
|
76
|
+
if (scenarios.length) {
|
|
77
|
+
lines.push('', 'Scenarios (for design_brain_consequences):')
|
|
78
|
+
for (const s of scenarios) lines.push(`- ${s.id} (${s.userId})`)
|
|
79
|
+
}
|
|
80
|
+
if (fs.existsSync(path.join(root, 'build-specs'))) lines.push('', 'Build specs: build-specs/')
|
|
81
|
+
const manifest = path.join(packagePaths.skillsDir, 'skills.json')
|
|
82
|
+
if (fs.existsSync(manifest)) {
|
|
83
|
+
lines.push('', 'Skills that ship with Hippocampus:')
|
|
84
|
+
for (const s of JSON.parse(fs.readFileSync(manifest, 'utf8')).skills || []) lines.push(`- ${s.id}: ${s.purpose || ''}`)
|
|
85
|
+
}
|
|
86
|
+
return lines.join('\n')
|
|
87
|
+
},
|
|
88
|
+
|
|
89
|
+
read: (relPath) => {
|
|
90
|
+
const target = path.resolve(root, String(relPath || '.'))
|
|
91
|
+
const rel = path.relative(root, target)
|
|
92
|
+
if (rel.startsWith('..') || path.isAbsolute(rel) || SECRET.test(rel) || !fs.existsSync(target)) {
|
|
93
|
+
return `Not found in the knowledge base project: ${relPath}`
|
|
94
|
+
}
|
|
95
|
+
// A folder returns a tree three levels deep, so that one call shows what is inside.
|
|
96
|
+
if (fs.statSync(target).isDirectory()) return clip(tree(target, 3).join('\n'))
|
|
97
|
+
return clip(fs.readFileSync(target, 'utf8'))
|
|
98
|
+
},
|
|
99
|
+
|
|
100
|
+
ask: async (question) => ask(question, { tools, env })
|
|
101
|
+
}
|
|
102
|
+
return tools
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
// A small model loop that answers with the package's own whats-known-about skill.
|
|
106
|
+
// Optional: it needs @google/genai installed, GEMINI_API_KEY and DESIGN_BRAIN_MODEL.
|
|
107
|
+
async function ask (question, { tools, env }) {
|
|
108
|
+
const apiKey = env.GEMINI_API_KEY || env.GOOGLE_API_KEY
|
|
109
|
+
const model = env.DESIGN_BRAIN_MODEL
|
|
110
|
+
if (!apiKey || !model) return 'design_brain_ask is off. Set GEMINI_API_KEY and DESIGN_BRAIN_MODEL, or use design_brain_brief.'
|
|
111
|
+
let genai
|
|
112
|
+
try {
|
|
113
|
+
genai = await import('@google/genai')
|
|
114
|
+
} catch {
|
|
115
|
+
return 'design_brain_ask needs the @google/genai package. Run `npm install @google/genai` in this project, or use design_brain_brief.'
|
|
116
|
+
}
|
|
117
|
+
const { GoogleGenAI, Type } = genai
|
|
118
|
+
const skill = fs.readFileSync(path.join(packagePaths.skillsDir, 'whats-known-about', 'SKILL.md'), 'utf8')
|
|
119
|
+
.split('---').slice(2).join('---')
|
|
120
|
+
const systemInstruction = [
|
|
121
|
+
'You answer questions about this design knowledge base for another agent that is building the service.',
|
|
122
|
+
'Use design_brain_brief first when the question is about a user, journey or feature. Then use known, consequences and read for detail.',
|
|
123
|
+
'Rules: every claim names its record ID. Keep assumptions apart from research. Say plainly what the knowledge base does not cover. Do not guess. Answer in 400 words or fewer.',
|
|
124
|
+
'Follow this skill:',
|
|
125
|
+
skill
|
|
126
|
+
].join('\n')
|
|
127
|
+
const loop = {
|
|
128
|
+
design_brain_brief: { run: (a) => tools.brief(a.subject), params: { subject: Type.STRING } },
|
|
129
|
+
design_brain_known: { run: (a) => tools.known(a.topic), params: { topic: Type.STRING } },
|
|
130
|
+
design_brain_consequences: { run: (a) => tools.consequences(a.scenarioId), params: { scenarioId: Type.STRING } },
|
|
131
|
+
design_brain_read: { run: (a) => tools.read(a.path), params: { path: Type.STRING } }
|
|
132
|
+
}
|
|
133
|
+
const functionDeclarations = Object.entries(loop).map(([name, t]) => ({
|
|
134
|
+
name,
|
|
135
|
+
description: name.replace(TOOL_PREFIX, ''),
|
|
136
|
+
parameters: { type: Type.OBJECT, properties: Object.fromEntries(Object.entries(t.params).map(([k, type]) => [k, { type }])), required: Object.keys(t.params) }
|
|
137
|
+
}))
|
|
138
|
+
const chat = new GoogleGenAI({ apiKey }).chats.create({ model, config: { systemInstruction, tools: [{ functionDeclarations }] } })
|
|
139
|
+
let response = await chat.sendMessage({ message: question })
|
|
140
|
+
// Stop after 12 rounds of tool calls, so that one question cannot run for ever.
|
|
141
|
+
for (let round = 0; round < 12 && response.functionCalls?.length; round++) {
|
|
142
|
+
const parts = response.functionCalls.map((call) => ({
|
|
143
|
+
functionResponse: { name: call.name, response: { result: loop[call.name]?.run(call.args || {}) ?? 'Unknown tool.' } }
|
|
144
|
+
}))
|
|
145
|
+
response = await chat.sendMessage({ message: parts })
|
|
146
|
+
}
|
|
147
|
+
// At the limit, turn tools off so that the model must answer with what it found.
|
|
148
|
+
if (response.functionCalls?.length || !response.text) {
|
|
149
|
+
response = await chat.sendMessage({
|
|
150
|
+
message: 'Stop searching. Answer now with what you found, and say plainly what the knowledge base does not cover.',
|
|
151
|
+
config: { toolConfig: { functionCallingConfig: { mode: 'NONE' } } }
|
|
152
|
+
})
|
|
153
|
+
}
|
|
154
|
+
return response.text || 'No answer.'
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
function createServer (ctx, { env = process.env, version = require('../package.json').version } = {}) {
|
|
158
|
+
const { McpServer } = require('@modelcontextprotocol/sdk/server/mcp.js')
|
|
159
|
+
const tools = createTools(ctx, { env })
|
|
160
|
+
const logFile = env.DESIGN_BRAIN_MCP_LOG
|
|
161
|
+
const reply = (name, arg, text) => {
|
|
162
|
+
if (logFile) fs.appendFileSync(logFile, `\n=== ${name}(${arg}) -> ${text.length} chars\n${text.slice(0, 3000)}\n`)
|
|
163
|
+
return { content: [{ type: 'text', text }] }
|
|
164
|
+
}
|
|
165
|
+
const server = new McpServer({ name: 'design_brain', version })
|
|
166
|
+
server.registerTool(`${TOOL_PREFIX}brief`, {
|
|
167
|
+
description: "Start here for a feature, journey or user role (for example 'paramedic' or 'discharge coordinator'). One brief with the needs, scenarios, journey steps, build spec acceptance criteria, screens, decisions, assumptions and insights, each with its record ID. No model.",
|
|
168
|
+
inputSchema: { subject: z.string() }
|
|
169
|
+
}, async ({ subject }) => reply('brief', subject, tools.brief(subject)))
|
|
170
|
+
server.registerTool(`${TOOL_PREFIX}known`, {
|
|
171
|
+
description: "What the knowledge base already holds on a topic: findings with round, date and confidence, assumptions kept apart, what was built on them, and whether nothing found means nobody asked. Use short topics, for example 'oxygen'.",
|
|
172
|
+
inputSchema: { topic: z.string() }
|
|
173
|
+
}, async ({ topic }) => reply('known', topic, tools.known(topic)))
|
|
174
|
+
server.registerTool(`${TOOL_PREFIX}consequences`, {
|
|
175
|
+
description: 'Run a new or changed journey (a scenario id) against the users the knowledge base already knows: who stands on the same ground, the decisions already taken there, weak ground, and questions nobody has asked. Candidates, not verdicts.',
|
|
176
|
+
inputSchema: { scenarioId: z.string() }
|
|
177
|
+
}, async ({ scenarioId }) => reply('consequences', scenarioId, tools.consequences(scenarioId)))
|
|
178
|
+
server.registerTool(`${TOOL_PREFIX}overview`, {
|
|
179
|
+
description: 'A map of the knowledge base: record counts, scenario ids, build specs and the skills that ship with Hippocampus.',
|
|
180
|
+
inputSchema: {}
|
|
181
|
+
}, async () => reply('overview', '', tools.overview()))
|
|
182
|
+
server.registerTool(`${TOOL_PREFIX}read`, {
|
|
183
|
+
description: "Read a file, or see a folder as a tree, in the knowledge base project. Use a path relative to its root, for example 'build-specs'. Secrets such as .env are never returned.",
|
|
184
|
+
inputSchema: { path: z.string() }
|
|
185
|
+
}, async ({ path: p }) => reply('read', p, tools.read(p)))
|
|
186
|
+
server.registerTool(`${TOOL_PREFIX}ask`, {
|
|
187
|
+
description: 'Ask a question in plain words. A model searches the knowledge base with the whats-known-about skill and answers with record IDs. Slower than brief (up to a minute). Needs GEMINI_API_KEY and DESIGN_BRAIN_MODEL.',
|
|
188
|
+
inputSchema: { question: z.string() }
|
|
189
|
+
}, async ({ question }) => reply('ask', question, await tools.ask(question)))
|
|
190
|
+
return server
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
module.exports = { createServer, createTools, TOOL_PREFIX }
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@hippo-digital/hippocampus",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.3.0",
|
|
4
4
|
"description": "A design-knowledge base for NHS Prototype Kit projects: research, insights, needs, journeys and screens, traceable end to end.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"main": "index.js",
|
|
@@ -32,6 +32,7 @@
|
|
|
32
32
|
"prepublishOnly": "node ../../scripts/check-release.js"
|
|
33
33
|
},
|
|
34
34
|
"dependencies": {
|
|
35
|
+
"@modelcontextprotocol/sdk": "^1.30.1",
|
|
35
36
|
"adm-zip": "^0.5.18",
|
|
36
37
|
"fast-xml-parser": "^5.9.3",
|
|
37
38
|
"marked": "^18.0.13",
|
|
@@ -42,9 +43,15 @@
|
|
|
42
43
|
"sass": "^1.80.0"
|
|
43
44
|
},
|
|
44
45
|
"peerDependencies": {
|
|
46
|
+
"@google/genai": "^2.24.0",
|
|
45
47
|
"nhsuk-frontend": ">=10.5.1",
|
|
46
48
|
"nhsuk-prototype-kit": ">=8.3.0"
|
|
47
49
|
},
|
|
50
|
+
"peerDependenciesMeta": {
|
|
51
|
+
"@google/genai": {
|
|
52
|
+
"optional": true
|
|
53
|
+
}
|
|
54
|
+
},
|
|
48
55
|
"engines": {
|
|
49
56
|
"node": ">=22.16.0"
|
|
50
57
|
},
|
|
@@ -65,7 +72,8 @@
|
|
|
65
72
|
"user-research",
|
|
66
73
|
"knowledge-base",
|
|
67
74
|
"service-design",
|
|
68
|
-
"accessibility"
|
|
75
|
+
"accessibility",
|
|
76
|
+
"mcp"
|
|
69
77
|
],
|
|
70
78
|
"author": "Hippo Digital",
|
|
71
79
|
"publishConfig": {
|
package/scripts/mcp.js
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
const http = require('http')
|
|
3
|
+
const { createContextOrExit } = require('../lib/context')
|
|
4
|
+
|
|
5
|
+
// hippocampus mcp [--stdio] [--port N] [--root <dir>]
|
|
6
|
+
//
|
|
7
|
+
// Serve this knowledge base to agents over MCP, read-only. By default it runs
|
|
8
|
+
// as its own HTTP service on http://127.0.0.1:3100/mcp, so several agents can
|
|
9
|
+
// share it; --stdio is for a client that starts the server itself. It binds to
|
|
10
|
+
// localhost only. See lib/mcp-server.js for the tools.
|
|
11
|
+
|
|
12
|
+
const USAGE = 'Usage: hippocampus mcp [--stdio] [--port N] [--root <dir>]'
|
|
13
|
+
const argv = process.argv.slice(2)
|
|
14
|
+
|
|
15
|
+
let stdio = false
|
|
16
|
+
let help = false
|
|
17
|
+
let port = Number(process.env.DESIGN_BRAIN_MCP_PORT || 3100)
|
|
18
|
+
for (let i = 0; i < argv.length; i++) {
|
|
19
|
+
const arg = argv[i]
|
|
20
|
+
if (arg === '--root') { i++; continue }
|
|
21
|
+
if (arg.startsWith('--root=')) continue
|
|
22
|
+
if (arg === '--stdio') stdio = true
|
|
23
|
+
else if (arg === '--port') port = Number(argv[++i])
|
|
24
|
+
else if (arg === '--help' || arg === '-h') help = true
|
|
25
|
+
else { console.error(`Unknown option: ${arg}\n${USAGE}`); process.exit(1) }
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
// Load the SDK before anything else, --help included, so a broken install
|
|
29
|
+
// says so rather than printing usage for a command that cannot run.
|
|
30
|
+
let createServer
|
|
31
|
+
try {
|
|
32
|
+
({ createServer } = require('../lib/mcp-server'))
|
|
33
|
+
require.resolve('@modelcontextprotocol/sdk/server/mcp.js')
|
|
34
|
+
} catch (error) {
|
|
35
|
+
console.error(`The MCP server could not load: ${error.message.split('\n')[0]}`)
|
|
36
|
+
process.exit(1)
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
if (help) {
|
|
40
|
+
console.log(`${USAGE}
|
|
41
|
+
|
|
42
|
+
Serves this knowledge base to agents over MCP, read-only, as design_brain_* tools.
|
|
43
|
+
(default) HTTP on http://127.0.0.1:<port>/mcp (DESIGN_BRAIN_MCP_PORT, default 3100)
|
|
44
|
+
--stdio for a client that starts the server itself
|
|
45
|
+
--port N another port
|
|
46
|
+
|
|
47
|
+
design_brain_ask needs GEMINI_API_KEY and DESIGN_BRAIN_MODEL, and @google/genai installed.
|
|
48
|
+
DESIGN_BRAIN_MCP_LOG=<file> appends each tool call and its answer to that file.`)
|
|
49
|
+
process.exit(0)
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
const ctx = createContextOrExit({ argv })
|
|
53
|
+
try {
|
|
54
|
+
ctx.requireProjects()
|
|
55
|
+
} catch (error) {
|
|
56
|
+
console.error(error.message)
|
|
57
|
+
process.exit(1)
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
async function main () {
|
|
61
|
+
if (stdio) {
|
|
62
|
+
const { StdioServerTransport } = require('@modelcontextprotocol/sdk/server/stdio.js')
|
|
63
|
+
await createServer(ctx).connect(new StdioServerTransport())
|
|
64
|
+
return
|
|
65
|
+
}
|
|
66
|
+
if (!Number.isInteger(port) || port <= 0) { console.error('--port needs a port number.'); process.exit(1) }
|
|
67
|
+
const { StreamableHTTPServerTransport } = require('@modelcontextprotocol/sdk/server/streamableHttp.js')
|
|
68
|
+
http.createServer(async (req, res) => {
|
|
69
|
+
if (req.url !== '/mcp') { res.writeHead(404).end(); return }
|
|
70
|
+
// Stateless: one server and transport for each request.
|
|
71
|
+
const server = createServer(ctx)
|
|
72
|
+
const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: undefined })
|
|
73
|
+
res.on('close', () => { transport.close(); server.close() })
|
|
74
|
+
let body = ''
|
|
75
|
+
for await (const chunk of req) body += chunk
|
|
76
|
+
try {
|
|
77
|
+
await server.connect(transport)
|
|
78
|
+
await transport.handleRequest(req, res, body ? JSON.parse(body) : undefined)
|
|
79
|
+
} catch (error) {
|
|
80
|
+
if (!res.headersSent) res.writeHead(400, { 'content-type': 'application/json' })
|
|
81
|
+
res.end(JSON.stringify({ jsonrpc: '2.0', error: { code: -32700, message: error.message }, id: null }))
|
|
82
|
+
}
|
|
83
|
+
}).listen(port, '127.0.0.1', () => console.error(`Hippocampus MCP server for ${ctx.root}\n http://127.0.0.1:${port}/mcp`))
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
main().catch((error) => { console.error(error.message); process.exit(1) })
|