@openora/mcp 0.4.1-canary.43 → 0.4.1-canary.430

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/main.js CHANGED
@@ -5,7 +5,55 @@ import { existsSync, readFileSync } from 'node:fs';
5
5
  import { execSync } from 'node:child_process';
6
6
  import { dirname, join, parse } from 'node:path';
7
7
  import { fileURLToPath } from 'node:url';
8
+ import { buildDepGraph, impactOf } from './dep-graph.js';
9
+ import { classifyIntent } from './intent.js';
10
+ import { findCoreSourceRoot, findSymbol, findUsages, outline, readSourceTree, LINE_WIDTH, } from './source.js';
8
11
  const here = dirname(fileURLToPath(import.meta.url));
12
+ const ownPackage = JSON.parse(readFileSync(join(here, '..', 'package.json'), 'utf8'));
13
+ const formatMethods = (a) => a.methods?.length ? ` { ${a.methods.join(', ')} }` : '';
14
+ const formatIam = (iam) => iam ? `${iam.resource}:${iam.action}` : '(non-literal)';
15
+ function formatAgentTool(t) {
16
+ return [
17
+ `- ${t.id} [${t.class ?? '?'}, v${t.schemaVersion ?? '?'}, iam ${formatIam(t.iam)}, module ${t.module}]`,
18
+ ...(t.title || t.description
19
+ ? [` ${[t.title, t.description].filter(Boolean).join(' - ')}`]
20
+ : []),
21
+ ];
22
+ }
23
+ function formatAgentAction(a) {
24
+ const reversibility = a.reversible === null ? 'reversible ?' : a.reversible ? 'reversible' : 'irreversible';
25
+ const benefit = a.benefitsPlayer === null
26
+ ? ', benefits player ?'
27
+ : a.benefitsPlayer
28
+ ? ', benefits player'
29
+ : a.benefitsPlayerWhen
30
+ ? `, benefits player when ${a.benefitsPlayerWhen.field} is ${a.benefitsPlayerWhen.values.join(' or ')}`
31
+ : '';
32
+ const distinct = a.distinctBy ? `, distinct by ${a.distinctBy}` : '';
33
+ return [
34
+ `- ${a.id} [${reversibility}${benefit}${distinct}, v${a.schemaVersion ?? '?'}, iam ${formatIam(a.iam)}, module ${a.module}]`,
35
+ ...(a.title || a.description
36
+ ? [` ${[a.title, a.description].filter(Boolean).join(' - ')}`]
37
+ : []),
38
+ ];
39
+ }
40
+ const containsIgnoreCase = (query, ...fields) => fields.some((f) => f.toLowerCase().includes(query.toLowerCase()));
41
+ // `packages/core/src/promo/bonus/plugin.ts` -> `promo/bonus`; test files are not bindings.
42
+ function bindingPlugins(a) {
43
+ return a.boundIn
44
+ .filter((p) => p.endsWith('/plugin.ts'))
45
+ .map((p) => p.replace(/^packages\/core\/src\//, '').replace(/\/plugin\.ts$/, ''));
46
+ }
47
+ function formatAdapter(a) {
48
+ const plugins = bindingPlugins(a);
49
+ const bound = plugins.length > 0
50
+ ? `bound in ${plugins.join(', ')}`
51
+ : a.status === 'wired'
52
+ ? 'bound in the core runtime'
53
+ : 'stub - bind your implementation';
54
+ return `- ${a.category}: ${a.interface}${formatMethods(a)} -> ${a.token} [${a.status}; ${bound}]`;
55
+ }
56
+ const SCHEMA_MATCH_LIMIT = 30;
9
57
  const NOT_FOUND_MESSAGE = 'catalog.json not found - run `pnpm regen` in the platform repo, or set OSS_CATALOG to its path.';
10
58
  function catalogCandidates() {
11
59
  const candidates = [];
@@ -54,54 +102,56 @@ function withCatalog(fn) {
54
102
  }
55
103
  const server = new McpServer({
56
104
  name: 'oss',
57
- version: '0.1.0',
105
+ version: ownPackage.version,
58
106
  });
59
107
  server.registerTool('catalog-overview', {
60
- description: 'START HERE. A concise "what can I extend" summary of the OSS igaming platform you are consuming: counts of modules/events/slots/schemas, the adapter swap-seam table (category/interface/token/status), and the igaming-config fields. Read this first to orient before drilling into the other tools.',
108
+ description: 'START HERE. A concise "what can I extend" summary of the OSS igaming platform you are consuming: counts of modules/events/schemas, the adapter swap-seam table (category/interface/token/status), and the igaming-config fields. Read this first to orient before drilling into the other tools.',
61
109
  inputSchema: {},
62
110
  }, withCatalog((c) => {
63
111
  const lines = ['=== OSS igaming platform catalog ==='];
64
112
  lines.push(`modules: ${c.modules.length} adapters: ${c.adapters.length} events: ${c.events.length} ` +
65
- `uiSlots: ${c.uiSlots.length} schemas: ${c.schemas.length} ` +
66
- `httpRoutes: ${c.httpRoutes.length}`);
67
- lines.push('\n--- Adapter seams (implement an interface, bind to the token) ---');
68
- for (const a of c.adapters) {
69
- lines.push(`- ${a.category}: ${a.interface} -> ${a.token} [${a.status}]`);
70
- }
113
+ `schemas: ${c.schemas.length} agent tools: ${c.agentTools?.length ?? 0} ` +
114
+ `action types: ${c.agentActions?.length ?? 0}`);
115
+ const stubs = c.adapters.filter((a) => a.status !== 'wired').map((a) => a.category);
116
+ lines.push('\n--- Adapter seams (details: list-adapters <query>) ---');
117
+ lines.push(c.adapters.map((a) => a.category).join(', '));
118
+ lines.push(`stubs awaiting an implementation: ${stubs.join(', ') || '(none)'}`);
119
+ lines.push(`\n--- Modules (details: describe-module <id>) ---`);
120
+ lines.push(c.modules.map((m) => m.id).join(', '));
71
121
  lines.push(`\n--- Config (${c.config.token}) ---`);
72
122
  for (const f of c.config.fields) {
73
123
  lines.push(`- ${f.key}${f.note ? `: ${f.note}` : ''}`);
74
124
  }
75
- lines.push('\nNext: list-adapters | list-routes | list-events | list-slots | describe-module <name> | schema-get <name> | get-config-schema');
125
+ lines.push('\nNext: list-adapters | list-routes | list-events | list-agent-tools | describe-module <name> | schema-get <name> | get-config-schema');
76
126
  return lines.join('\n');
77
127
  }));
78
128
  server.registerTool('list-adapters', {
79
- description: 'List the vendor adapter swap-seams (PSP/KYC/game/aggregator/geo-ip/notification). For each: the interface to implement, the DI token to bind it to, whether it is already wired or a stub awaiting an implementation, and where it is bound. Use this to find the integration point for a third-party vendor.',
80
- inputSchema: {},
81
- }, withCatalog((c) => {
82
- if (c.adapters.length === 0) {
83
- return 'No adapters in the catalog.';
84
- }
85
- const lines = ['=== Adapter seams ==='];
86
- for (const a of c.adapters) {
87
- lines.push(`\n${a.category} [${a.status}]`);
88
- lines.push(` interface: ${a.interface}`);
89
- lines.push(` token: ${a.token}`);
90
- if (a.boundIn.length > 0) {
91
- lines.push(` boundIn: ${a.boundIn.join(', ')}`);
92
- }
93
- else {
94
- lines.push(' boundIn: (none - stub; bind your implementation to the token)');
95
- }
129
+ description: 'List the vendor adapter swap-seams (PSP/KYC/game/aggregator/geo-ip/notification). For each: the interface to implement, the DI token to bind it to, whether it is already wired or a stub awaiting an implementation, and which module plugins bind it. Use this to find the integration point for a third-party vendor. Pass `query` (e.g. "withdrawal", "kyc") to keep the output short.',
130
+ inputSchema: {
131
+ query: z
132
+ .string()
133
+ .optional()
134
+ .describe('Case-insensitive filter on category, interface, token or binding module'),
135
+ },
136
+ }, async ({ query }) => {
137
+ const loaded = loadCatalog();
138
+ if (!loaded) {
139
+ return { content: [{ type: 'text', text: NOT_FOUND_MESSAGE }] };
96
140
  }
97
- return lines.join('\n');
98
- }));
141
+ const adapters = loaded.catalog.adapters.filter((a) => !query ||
142
+ containsIgnoreCase(query, a.category, a.interface, a.token, ...(a.methods ?? []), ...bindingPlugins(a)));
143
+ const text = adapters.length > 0
144
+ ? `=== Adapter seams (${adapters.length}) ===\n${adapters.map(formatAdapter).join('\n')}`
145
+ : `No adapter seam matches "${query}".`;
146
+ return { content: [{ type: 'text', text }] };
147
+ });
99
148
  server.registerTool('list-routes', {
100
- description: 'List oRPC route namespaces exposed by the platform modules. Pass `module` to scope to a single module. Includes top-level httpRoutes when present.',
149
+ description: 'List oRPC route namespaces exposed by the platform modules. Pass `module` to scope to a single module and `query` (e.g. "withdraw") to keep only matching routes.',
101
150
  inputSchema: {
102
151
  module: z.string().optional().describe('Module id to filter by (e.g. "wallet")'),
152
+ query: z.string().optional().describe('Case-insensitive substring of the route'),
103
153
  },
104
- }, async ({ module: mod }) => {
154
+ }, async ({ module: mod, query }) => {
105
155
  const loaded = loadCatalog();
106
156
  if (!loaded) {
107
157
  return { content: [{ type: 'text', text: NOT_FOUND_MESSAGE }] };
@@ -120,38 +170,56 @@ server.registerTool('list-routes', {
120
170
  }
121
171
  const lines = [];
122
172
  for (const m of modules) {
123
- if (m.routes.length > 0) {
124
- lines.push(`${m.id}:\n${m.routes.map((r) => ` ${r}`).join('\n')}`);
173
+ const routes = m.routes.filter((r) => !query || containsIgnoreCase(query, r));
174
+ if (routes.length > 0) {
175
+ lines.push(`${m.id}:\n${routes.map((r) => ` ${r}`).join('\n')}`);
125
176
  }
126
177
  }
127
- if (!mod && c.httpRoutes.length > 0) {
128
- lines.push(`httpRoutes:\n${c.httpRoutes.map((r) => ` ${r}`).join('\n')}`);
129
- }
130
- const text = lines.join('\n\n') || 'No routes defined in the catalog yet.';
178
+ const text = lines.join('\n\n') ||
179
+ (query ? `No route matches "${query}".` : 'No routes defined in the catalog yet.');
131
180
  return { content: [{ type: 'text', text }] };
132
181
  });
133
182
  server.registerTool('list-events', {
134
- description: 'List the cross-module domain events you can subscribe to (via ctx.events.on in a plugin) or that signal platform activity. Use this to find the event to hook into for side effects.',
135
- inputSchema: {},
136
- }, withCatalog((c) => {
137
- if (c.events.length === 0) {
138
- return 'No events in the catalog.';
139
- }
140
- return `=== Domain events (${c.events.length}) ===\n${c.events.map((e) => `- ${e}`).join('\n')}`;
141
- }));
142
- server.registerTool('list-slots', {
143
- description: 'List the named UI slots you can fill from a client-side UI plugin (ctx.<slot>.add(...)) to extend the backoffice without forking: nav items, table columns, dashboard tiles, detail sections. Includes each slot description and subject type.',
144
- inputSchema: {},
145
- }, withCatalog((c) => {
146
- if (c.uiSlots.length === 0) {
147
- return 'No UI slots in the catalog.';
183
+ description: 'List the cross-module domain events you can subscribe to (via ctx.events.on in a plugin) or that signal platform activity. Use this to find the event to hook into for side effects. Pass `query` (e.g. "withdrawal", "promo.bonus") to keep the output short.',
184
+ inputSchema: {
185
+ query: z.string().optional().describe('Case-insensitive substring of the event name'),
186
+ },
187
+ }, async ({ query }) => {
188
+ const loaded = loadCatalog();
189
+ if (!loaded) {
190
+ return { content: [{ type: 'text', text: NOT_FOUND_MESSAGE }] };
148
191
  }
149
- const lines = ['=== UI slots ==='];
150
- for (const s of c.uiSlots) {
151
- lines.push(`- ${s.name}${s.description ? ` # ${s.description}` : ''}`);
192
+ const events = loaded.catalog.events.filter((e) => !query || containsIgnoreCase(query, e));
193
+ const text = events.length > 0
194
+ ? `=== Domain events (${events.length}) ===\n${events.map((e) => `- ${e}`).join('\n')}`
195
+ : `No event matches "${query}".`;
196
+ return { content: [{ type: 'text', text }] };
197
+ });
198
+ server.registerTool('list-agent-tools', {
199
+ description: 'List the agent surface: MCP tools (read calls a model may make during a run) and action types (state changes a model may only propose; an idempotent executor runs them after approval). Each entry shows its IAM resource:action, schema version and owning module. Modules register them in plugin.ts with ctx.mcp.tool(defineMcpTool({...}), factory) and ctx.actions.register(defineActionType({...}), factory); consumers reach them only through the MCP_KERNEL token, which validates input, checks IAM, applies the output allow-list and audits every call. Pass `module` to scope to one module and `query` to match ids, titles and descriptions.',
200
+ inputSchema: {
201
+ module: z.string().optional().describe('Module id to filter by (e.g. "wallet")'),
202
+ query: z
203
+ .string()
204
+ .optional()
205
+ .describe('Case-insensitive substring of the id, title or description'),
206
+ },
207
+ }, async ({ module: mod, query }) => {
208
+ const loaded = loadCatalog();
209
+ if (!loaded) {
210
+ return { content: [{ type: 'text', text: NOT_FOUND_MESSAGE }] };
152
211
  }
153
- return lines.join('\n');
154
- }));
212
+ const c = loaded.catalog;
213
+ const matches = (e) => (!mod || e.module === mod) &&
214
+ (!query || containsIgnoreCase(query, e.id, e.title ?? '', e.description ?? ''));
215
+ const tools = (c.agentTools ?? []).filter(matches);
216
+ const actions = (c.agentActions ?? []).filter(matches);
217
+ const lines = [`=== Agent tools (${tools.length}) ===`];
218
+ lines.push(...(tools.length > 0 ? tools.flatMap(formatAgentTool) : ['(none)']));
219
+ lines.push(`\n=== Agent action types (${actions.length}) ===`);
220
+ lines.push(...(actions.length > 0 ? actions.flatMap(formatAgentAction) : ['(none)']));
221
+ return { content: [{ type: 'text', text: lines.join('\n') }] };
222
+ });
155
223
  server.registerTool('describe-module', {
156
224
  description: "Describe one platform module from the catalog: its group (player/backoffice/platform), Drizzle tables, and oRPC routes. Use this to understand a module's surface before extending or integrating with it.",
157
225
  inputSchema: { name: z.string().describe('Module id (e.g. "wallet", "gaming")') },
@@ -176,12 +244,31 @@ server.registerTool('describe-module', {
176
244
  const lines = [`=== Module: ${m.id} (${m.group}) ===`];
177
245
  lines.push(`\n--- Tables ---\n${m.tables.length > 0 ? m.tables.map((t) => `- ${t}`).join('\n') : '(none)'}`);
178
246
  lines.push(`\n--- Routes ---\n${m.routes.length > 0 ? m.routes.map((r) => `- ${r}`).join('\n') : '(none)'}`);
247
+ const eventSegments = [m.id, m.id.replaceAll('-', '_')];
248
+ const events = c.events.filter((e) => e.split('.').some((s) => eventSegments.includes(s)));
249
+ lines.push(`\n--- Events named after this module ---\n${events.length > 0 ? events.map((e) => `- ${e}`).join('\n') : '(none - try list-events query=<word>)'}`);
250
+ const seams = c.adapters.filter((a) => bindingPlugins(a).some((p) => p === m.id || p.endsWith(`/${m.id}`)));
251
+ if (seams.length > 0) {
252
+ const seamLines = seams.map((a) => `- ${a.category} -> ${a.token}`).join('\n');
253
+ lines.push(`\n--- Adapter seams this module binds or reads (methods: list-adapters query=<category>) ---\n${seamLines}`);
254
+ }
255
+ const tools = (c.agentTools ?? []).filter((t) => t.module === m.id);
256
+ const actions = (c.agentActions ?? []).filter((a) => a.module === m.id);
257
+ if (tools.length > 0) {
258
+ lines.push(`\n--- Agent tools ---\n${tools.flatMap(formatAgentTool).join('\n')}`);
259
+ }
260
+ if (actions.length > 0) {
261
+ lines.push(`\n--- Agent action types ---\n${actions.flatMap(formatAgentAction).join('\n')}`);
262
+ }
179
263
  return { content: [{ type: 'text', text: lines.join('\n') }] };
180
264
  });
181
265
  server.registerTool('schema-get', {
182
266
  description: 'Locate a Zod contract schema by name and return the file that defines it. The actual shape is read from the package types you have installed; this tells you WHERE the schema lives so you can import it.',
183
267
  inputSchema: {
184
- name: z.string().describe('Schema name, e.g. "WalletBalance" or "WalletBalanceSchema"'),
268
+ name: z
269
+ .string()
270
+ .min(1)
271
+ .describe('Schema name, e.g. "WalletBalance" or "WalletBalanceSchema"'),
185
272
  },
186
273
  }, async ({ name }) => {
187
274
  const loaded = loadCatalog();
@@ -194,18 +281,134 @@ server.registerTool('schema-get', {
194
281
  if (hit) {
195
282
  return { content: [{ type: 'text', text: `${hit.name}\n${hit.file}` }] };
196
283
  }
197
- const list = c.schemas
198
- .map((s) => s.name)
199
- .sort()
200
- .join(', ');
201
- return {
202
- content: [
203
- {
204
- type: 'text',
205
- text: `Schema "${name}" not found.\n\nAvailable schemas:\n${list}`,
206
- },
207
- ],
208
- };
284
+ const close = c.schemas.filter((s) => containsIgnoreCase(name, s.name));
285
+ const shown = close
286
+ .slice(0, SCHEMA_MATCH_LIMIT)
287
+ .map((s) => `- ${s.name} ${s.file}`)
288
+ .join('\n');
289
+ const more = close.length > SCHEMA_MATCH_LIMIT
290
+ ? `\n(${close.length - SCHEMA_MATCH_LIMIT} more - narrow the name)`
291
+ : '';
292
+ const text = close.length > 0
293
+ ? `No schema named "${name}". Names containing it:\n${shown}${more}`
294
+ : `No schema name contains "${name}". Try a shorter word (e.g. "Withdraw").`;
295
+ return { content: [{ type: 'text', text }] };
296
+ });
297
+ const USAGE_LIMIT = 40;
298
+ const SYMBOL_LOCATION_LIMIT = 5;
299
+ // Read on every call (~35 ms for core): a paired change edits the very files this serves.
300
+ function loadSource() {
301
+ const loaded = loadCatalog();
302
+ const root = process.env['OSS_SOURCE'] ?? (loaded ? findCoreSourceRoot(loaded.path) : null);
303
+ if (!root || !existsSync(root)) {
304
+ return 'Platform source not found - it is read from a linked platform checkout (packages/core/src). Set OSS_SOURCE to that folder.';
305
+ }
306
+ return { root, files: readSourceTree(root) };
307
+ }
308
+ const textReply = (text) => ({ content: [{ type: 'text', text }] });
309
+ const namesInput = (example) => z
310
+ .array(z.string().min(2))
311
+ .min(1)
312
+ .max(10)
313
+ .describe(`One or more names, looked up together in one call, e.g. ${example}`);
314
+ function usagesOf(source, name, mod, includeTests) {
315
+ const usages = findUsages(source.files, name, { module: mod, includeTests });
316
+ if (usages.length === 0) {
317
+ return `No usage of "${name}"${mod ? ` under ${mod}/` : ''}.`;
318
+ }
319
+ const shown = usages.slice(0, USAGE_LIMIT).map((u) => `${u.path}:${u.line} ${u.text}`);
320
+ const more = usages.length > USAGE_LIMIT
321
+ ? `\n(${usages.length - USAGE_LIMIT} more - pass module=<folder> to narrow)`
322
+ : '';
323
+ return `=== ${usages.length} usages of ${name} ===\n${shown.join('\n')}${more}`;
324
+ }
325
+ server.registerTool('find-usages', {
326
+ description: 'Find where identifiers are used: a DI token (WALLET_COMMANDS), a function, a type, an event or route id. Whole-word match over packages/core/src, comment lines and tests skipped. Returns `file:line code`, capped. Pass every name you need in one call. Use it instead of grepping the platform source.',
327
+ inputSchema: {
328
+ names: namesInput('["WALLET_COMMANDS", "withdraw"]'),
329
+ module: z
330
+ .string()
331
+ .optional()
332
+ .describe('Only files under this folder, for every name, e.g. "wallet" or "promo/bonus"'),
333
+ includeTests: z.boolean().optional().describe('Also search test files (default false)'),
334
+ },
335
+ }, async ({ names, module: mod, includeTests }) => {
336
+ const source = loadSource();
337
+ if (typeof source === 'string') {
338
+ return textReply(source);
339
+ }
340
+ const sections = [...new Set(names)].map((name) => usagesOf(source, name, mod, includeTests));
341
+ return textReply([`(paths under ${source.root})`, ...sections].join('\n\n'));
342
+ });
343
+ function symbolOf(source, name, file, maxLines) {
344
+ const hits = findSymbol(source.files, name, { file });
345
+ if (hits.length === 0) {
346
+ return `No declaration of "${name}"${file ? ` in files matching ${file}` : ''}. Try find-usages names=["${name.split('.').pop()}"].`;
347
+ }
348
+ if (hits.length > SYMBOL_LOCATION_LIMIT) {
349
+ const where = hits
350
+ .slice(0, USAGE_LIMIT)
351
+ .map((h) => `${h.path}:${h.line} ${(h.body[0] ?? '').trim().slice(0, LINE_WIDTH)}`);
352
+ if (hits.length > USAGE_LIMIT) {
353
+ where.push(`(${hits.length - USAGE_LIMIT} more)`);
354
+ }
355
+ return `${hits.length} declarations of "${name}" - pass file=<path part>${name.includes('.') ? '' : ` or Owner.${name}`}:\n${where.join('\n')}`;
356
+ }
357
+ return hits
358
+ .map((h) => {
359
+ const path = `${source.root}/${h.path}`;
360
+ const head = `--- ${path}:${h.line}-${h.line + h.body.length - 1} ---`;
361
+ if (h.body.length <= maxLines) {
362
+ return `${head}\n${h.body.map((l) => l.slice(0, LINE_WIDTH)).join('\n')}`;
363
+ }
364
+ const shape = outline(h);
365
+ const shown = shape.slice(0, maxLines).map((l) => l.slice(0, LINE_WIDTH));
366
+ const nextLine = shape[maxLines]?.split(':')[0];
367
+ const rest = nextLine
368
+ ? `${shape.length - maxLines} more outline lines; Read ${path} offset=${nextLine} limit=${h.line + h.body.length - Number(nextLine)} for the rest`
369
+ : `Read ${path} offset=<line> limit=<n> for a part`;
370
+ return [
371
+ `${head} (outline: ${h.body.length} lines is over maxLines=${maxLines})`,
372
+ ...shown,
373
+ `... (${rest}, or raise maxLines for the whole body)`,
374
+ ].join('\n');
375
+ })
376
+ .join('\n\n');
377
+ }
378
+ server.registerTool('get-symbol', {
379
+ description: 'Print the source of platform declarations: a function, const, schema, type, interface, class or one method with `Owner.method` (e.g. "WalletService.withdraw", "WithdrawInputSchema"). A body over maxLines comes back as a numbered outline (members, or statements and their if/throw/await lines). Pass every name you need in one call. Use it instead of grepping for the definition and reading the file around it.',
380
+ inputSchema: {
381
+ names: namesInput('["WalletService.withdraw", "WithdrawInputSchema"]'),
382
+ file: z
383
+ .string()
384
+ .optional()
385
+ .describe('Path substring to pick one definition, for every name, e.g. "wallet/service"'),
386
+ maxLines: z
387
+ .number()
388
+ .int()
389
+ .min(5)
390
+ .max(400)
391
+ .optional()
392
+ .describe('Longest body printed whole, per declaration (default 80); longer ones come back as an outline'),
393
+ },
394
+ }, async ({ names, file, maxLines = 80 }) => {
395
+ const source = loadSource();
396
+ if (typeof source === 'string') {
397
+ return textReply(source);
398
+ }
399
+ // A batch prints no more than one name could: its hits at maxLines each.
400
+ const budget = SYMBOL_LOCATION_LIMIT * maxLines;
401
+ let used = 0;
402
+ const sections = [...new Set(names)].map((name) => {
403
+ const section = symbolOf(source, name, file, maxLines);
404
+ const size = section.split('\n').length;
405
+ if (used > 0 && used + size > budget) {
406
+ return `(${name}: skipped, it would take this reply over ${budget} lines - ask for it in another call)`;
407
+ }
408
+ used += size;
409
+ return section;
410
+ });
411
+ return textReply(sections.join('\n\n'));
209
412
  });
210
413
  server.registerTool('get-config-schema', {
211
414
  description: 'Return the igaming-config surface: the DI token, the source file that defines it, and each configurable field with its note. Use this to learn what a consumer can configure (branding, currencies, jurisdictions, enabled modules, limits, ...).',
@@ -220,23 +423,6 @@ server.registerTool('get-config-schema', {
220
423
  }
221
424
  return lines.join('\n');
222
425
  }));
223
- function classifyIntent(ask) {
224
- const a = ` ${ask.toLowerCase()} `;
225
- const has = (re) => re.test(a);
226
- if (has(/\b(payment|psp|stripe|adyen|kyc|onfido|sms|email|notification|vendor|adapter|gateway)\b/)) {
227
- return 'adapter';
228
- }
229
- if (has(/\b(page|screen|dashboard|view|frontend|admin panel|backoffice page|player page)\b/)) {
230
- return 'ui-page';
231
- }
232
- if (has(/\b(endpoint|route|procedure|api method|rpc)\b/)) {
233
- return 'route';
234
- }
235
- if (has(/\b(feature|module|tournament|leaderboard|jackpot|loyalty|bonus|cashback|mission|reward)\b/)) {
236
- return 'feature';
237
- }
238
- return 'unsure';
239
- }
240
426
  function buildConsumerPlaybook(kind, ctx) {
241
427
  const moduleList = ctx.modules.length
242
428
  ? ctx.modules.map((m) => `- ${m}`).join('\n')
@@ -245,7 +431,7 @@ function buildConsumerPlaybook(kind, ctx) {
245
431
  case 'feature':
246
432
  return [
247
433
  '## Where it goes',
248
- 'New behavior in a consumer repo -> an overlay plugin (`pnpm gen plugin`). It can add routes, subscribe to events, rebind adapters, and fill UI slots without touching OSS core.',
434
+ 'New behavior in a consumer repo -> an overlay plugin (`pnpm gen plugin`). It can add routes, subscribe to events, and rebind adapters without touching OSS core.',
249
435
  'If this is a new business domain that should be in the OSS platform itself, open an issue on the OSS repo instead.',
250
436
  '',
251
437
  '## Existing platform modules you can hook into',
@@ -253,15 +439,15 @@ function buildConsumerPlaybook(kind, ctx) {
253
439
  '',
254
440
  '## Playbook',
255
441
  '1. Spawn the `expert` agent (Task tool) to turn this ask into requirements + acceptance criteria (player journey, jurisdiction rules, edge cases). Skip only for a trivial change.',
256
- '2. Spawn the `builder` agent to implement: `pnpm gen plugin`, then in `register(ctx)` add routes (`ctx.routers.add`), subscribe to events (`ctx.events.on`), fill slots (`ctx.slots.fill`).',
442
+ '2. Spawn the `builder` agent to implement: `pnpm gen plugin`, then in `register(ctx)` add routes (`ctx.routers.add`) and subscribe to events (`ctx.events.on`).',
257
443
  '3. Register the plugin in `extensions.config.ts` at the repo root.',
258
- '4. Spawn the `qa` agent to write/run a Playwright E2E test for the acceptance criteria.',
444
+ '4. Spawn the `tester` agent to write/run a Playwright E2E test for the acceptance criteria.',
259
445
  '5. Run `pnpm check:types && pnpm check:lint`.',
260
446
  '',
261
447
  '## Agents',
262
448
  '- `expert` - requirements + AC (advisory, no code)',
263
449
  '- `builder` - implements the overlay',
264
- '- `qa` - E2E test + bug triage (OSS-core vs overlay)',
450
+ '- `tester` - E2E test + bug triage (OSS-core vs overlay)',
265
451
  ].join('\n');
266
452
  case 'adapter':
267
453
  return [
@@ -286,21 +472,16 @@ function buildConsumerPlaybook(kind, ctx) {
286
472
  case 'ui-page':
287
473
  return [
288
474
  '## Where it goes',
289
- 'The platform is headless - pages live in your own frontend repo and consume the api via `@openora/core/react`. Fill named UI slots from a client-side UI plugin.',
290
- '',
291
- '## Named UI slots you can fill (via defineUIPlugin)',
292
- ctx.slots.length
293
- ? ctx.slots.map((s) => `- ${s}`).join('\n')
294
- : '- (run list-slots for details)',
475
+ 'The platform is headless - pages live in your own frontend repo and consume the api via `@openora/core/react`.',
295
476
  '',
296
477
  '## Playbook',
297
- '1. Spawn the `builder` agent to implement the page in your frontend repo, or extend an existing surface via `defineUIPlugin` into a slot above.',
298
- '2. Spawn the `qa` agent to verify the page renders and behaves in a browser.',
478
+ '1. Spawn the `builder` agent to implement the page in your frontend repo.',
479
+ '2. Spawn the `tester` agent to verify the page renders and behaves in a browser.',
299
480
  '3. Run `pnpm check:types`.',
300
481
  '',
301
482
  '## Agents',
302
483
  '- `builder` - mounts/extends the page',
303
- '- `qa` - browser verification',
484
+ '- `tester` - browser verification',
304
485
  ].join('\n');
305
486
  case 'route':
306
487
  return [
@@ -329,7 +510,7 @@ function buildConsumerPlaybook(kind, ctx) {
329
510
  '## Agents available in this repo',
330
511
  '- `expert` - domain/product requirements (advisory)',
331
512
  '- `builder` - fullstack implementation',
332
- '- `qa` - E2E testing',
513
+ '- `tester` - E2E testing',
333
514
  ].join('\n');
334
515
  }
335
516
  }
@@ -365,7 +546,7 @@ const REQUIREMENTS_INTERVIEW = [
365
546
  'Then summarize the requirements back to the user as a short structured list and get an explicit yes before any building starts.',
366
547
  ].join('\n');
367
548
  server.registerTool('enhance-intent', {
368
- description: 'Turn a fuzzy "I want to build X" ask into a grounded, consumer-context brief. Uses the platform catalog (live module/adapter/slot list) to return a classified intent, a requirements checklist to collect from the user, a step-by-step playbook using the consumer pnpm gen commands, and an acceptance-criteria stub.',
549
+ description: 'Turn a fuzzy "I want to build X" ask into a grounded, consumer-context brief. Uses the platform catalog (live module and adapter list) to return a classified intent, a requirements checklist to collect from the user, a step-by-step playbook using the consumer pnpm gen commands, and an acceptance-criteria stub.',
369
550
  inputSchema: {
370
551
  ask: z
371
552
  .string()
@@ -382,7 +563,6 @@ server.registerTool('enhance-intent', {
382
563
  const ctx = {
383
564
  modules: catalog?.modules.map((m) => `${m.group}/${m.id}`) ?? [],
384
565
  tokens: catalog?.adapters.map((a) => a.token) ?? [],
385
- slots: catalog?.uiSlots.map((s) => s.name) ?? [],
386
566
  };
387
567
  const detected = kind && kind !== 'unsure' ? '' : ' (auto-detected)';
388
568
  const text = [
@@ -422,14 +602,13 @@ server.registerTool('start', {
422
602
  const tokens = catalog?.adapters.map((a) => a.token) ?? [];
423
603
  const role = [
424
604
  '## Your role',
425
- 'You are a requirements interviewer and orchestrator, NOT the implementer. Your one human-facing job is to collect thorough requirements from the user. Everything after that - scaffolding, code, tests - you delegate to the agents (`expert`, `builder`, `qa`) via the Task tool. Keep the user out of the loop after requirements are confirmed, except to resolve genuine decisions only they can make.',
605
+ 'You are a requirements interviewer and orchestrator, NOT the implementer. Your one human-facing job is to collect thorough requirements from the user. Everything after that - scaffolding, code, tests - you delegate to the agents (`expert`, `builder`, `tester`) via the Task tool. Keep the user out of the loop after requirements are confirmed, except to resolve genuine decisions only they can make.',
426
606
  ].join('\n');
427
607
  if (ask) {
428
608
  const resolved = classifyIntent(ask);
429
609
  const playbook = buildConsumerPlaybook(resolved, {
430
610
  modules,
431
611
  tokens,
432
- slots: catalog?.uiSlots.map((s) => s.name) ?? [],
433
612
  });
434
613
  return {
435
614
  content: [
@@ -480,7 +659,7 @@ server.registerTool('start', {
480
659
  'Call `enhance-intent` (ask = the confirmed requirements summary, kind = step 1). Then follow its playbook, which delegates to the agents:',
481
660
  '- `expert` formalizes requirements + acceptance criteria (and may surface gaps - if so, ask the user those, then continue).',
482
661
  '- `builder` implements (`pnpm gen ...`, code).',
483
- '- `qa` writes/runs the E2E test.',
662
+ '- `tester` writes/runs the E2E test.',
484
663
  'You orchestrate; you do not write feature code yourself.',
485
664
  '',
486
665
  `Platform modules: ${modules.join(', ') || '(catalog not loaded)'}`,
@@ -489,6 +668,86 @@ server.registerTool('start', {
489
668
  ],
490
669
  };
491
670
  });
671
+ let builtGraph = null;
672
+ // The repo's own graph: a prebuilt dep-graph.json at the root wins (CI writes one), else built
673
+ // once per server process - a full cruise takes seconds, not milliseconds.
674
+ function localGraph(rebuild) {
675
+ const prebuilt = join(process.cwd(), 'dep-graph.json');
676
+ if (!rebuild && existsSync(prebuilt)) {
677
+ return JSON.parse(readFileSync(prebuilt, 'utf8'));
678
+ }
679
+ if (rebuild || !builtGraph) {
680
+ builtGraph = buildDepGraph(process.cwd());
681
+ }
682
+ return builtGraph;
683
+ }
684
+ // Shipped with the package (built by the platform's publish job), so a consumer repo can follow
685
+ // a platform file into its own code without a platform checkout.
686
+ function platformGraph() {
687
+ const shipped = join(here, '..', 'docs', 'dep-graph.json');
688
+ return existsSync(shipped) ? JSON.parse(readFileSync(shipped, 'utf8')) : null;
689
+ }
690
+ server.registerTool('impact', {
691
+ description: 'Blast radius of a change: for each repo-relative file, the files that import it (transitively), and for a platform file (packages/core/src/...) the public @openora/* entry points it reaches plus the consumer files importing them. Use before editing a shared file, or to decide what to re-test after a change.',
692
+ inputSchema: {
693
+ files: z
694
+ .array(z.string())
695
+ .min(1)
696
+ .describe('Repo-relative paths, e.g. "apps/web/src/lib/x.ts"'),
697
+ depth: z
698
+ .number()
699
+ .int()
700
+ .min(1)
701
+ .max(10)
702
+ .optional()
703
+ .describe('Import hops to follow (default 4)'),
704
+ rebuild: z
705
+ .boolean()
706
+ .optional()
707
+ .describe('Re-cruise the repo instead of using a cached graph'),
708
+ },
709
+ }, async ({ files, depth = 4, rebuild = false }) => {
710
+ let local;
711
+ try {
712
+ local = localGraph(rebuild);
713
+ }
714
+ catch (error) {
715
+ return {
716
+ content: [{ type: 'text', text: `Could not build the graph: ${String(error)}` }],
717
+ };
718
+ }
719
+ const platform = platformGraph();
720
+ const list = (items, max = 40) => items.length === 0
721
+ ? ' (none)'
722
+ : items
723
+ .slice(0, max)
724
+ .map((i) => ` - ${i}`)
725
+ .join('\n') + (items.length > max ? `\n (+${items.length - max} more)` : '');
726
+ const sections = files.map((file) => {
727
+ const known = (g) => file in g.dependents || file in g.entryPoints || file in g.platform;
728
+ const onPlatform = platform && !known(local) && known(platform);
729
+ const impact = onPlatform
730
+ ? impactOf(platform, file, depth, local)
731
+ : impactOf(local, file, depth);
732
+ const lines = [
733
+ `=== ${file} ===`,
734
+ `Importers (${impact.importers.length}):`,
735
+ list(impact.importers),
736
+ ];
737
+ if (impact.specifiers.length > 0) {
738
+ lines.push(`Public entry points reached:`, list(impact.specifiers));
739
+ }
740
+ if (onPlatform) {
741
+ lines.push(`Files in this repo importing them:`, list(impact.consumerFiles));
742
+ }
743
+ const imports = local.platform[file];
744
+ if (imports?.length) {
745
+ lines.push(`Platform imports of this file:`, list(imports));
746
+ }
747
+ return lines.join('\n');
748
+ });
749
+ return { content: [{ type: 'text', text: sections.join('\n\n') }] };
750
+ });
492
751
  server.registerTool('dev:infra', {
493
752
  description: 'Start / stop / status local dev infrastructure via docker compose (postgres on :5432). Call before pnpm db:migrate or pnpm dev when the database is not reachable.',
494
753
  inputSchema: {