wuica-cli 0.0.0-stage → 0.1.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/LICENSE +661 -0
  2. package/README.md +546 -2
  3. package/bin/wuica-mcp.js +16 -0
  4. package/bin/wuica.js +25 -0
  5. package/dist/data/arch/ADL-P.bin.br +0 -0
  6. package/dist/data/arch/BDW.bin.br +0 -0
  7. package/dist/data/arch/CFL.bin.br +0 -0
  8. package/dist/data/arch/CLX.bin.br +0 -0
  9. package/dist/data/arch/HSW.bin.br +0 -0
  10. package/dist/data/arch/ICL.bin.br +0 -0
  11. package/dist/data/arch/ICX.bin.br +0 -0
  12. package/dist/data/arch/IVB.bin.br +0 -0
  13. package/dist/data/arch/KBL.bin.br +0 -0
  14. package/dist/data/arch/RKL.bin.br +0 -0
  15. package/dist/data/arch/SKL.bin.br +0 -0
  16. package/dist/data/arch/SKX.bin.br +0 -0
  17. package/dist/data/arch/SNB.bin.br +0 -0
  18. package/dist/data/arch/TGL.bin.br +0 -0
  19. package/dist/data/arch/ZEN3.bin.br +0 -0
  20. package/dist/data/uarch.json.br +0 -0
  21. package/dist/manifest.json +160 -0
  22. package/dist/wuica_asm.wasm.br +0 -0
  23. package/dist/wuica_wasm.wasm.br +0 -0
  24. package/index.d.ts +410 -0
  25. package/lib/archs.js +44 -0
  26. package/lib/cli.js +693 -0
  27. package/lib/core.js +36 -0
  28. package/lib/details.js +60 -0
  29. package/lib/examples.js +26 -0
  30. package/lib/files.js +40 -0
  31. package/lib/index.js +577 -0
  32. package/lib/insights.js +100 -0
  33. package/lib/mcp.js +366 -0
  34. package/lib/objfile.js +216 -0
  35. package/lib/thread-worker.js +49 -0
  36. package/lib/threads.js +235 -0
  37. package/lib/wasm.js +246 -0
  38. package/lib/web/accum.js +202 -0
  39. package/lib/web/asm-regions.js +415 -0
  40. package/lib/web/assembler.js +188 -0
  41. package/lib/web/caveats.js +214 -0
  42. package/lib/web/examples.js +99 -0
  43. package/lib/web/loop-find.js +492 -0
  44. package/lib/web/showcase.js +368 -0
  45. package/lib/whatif.js +136 -0
  46. package/licenses/LICENSE-LLVM.txt +279 -0
  47. package/licenses/LICENSE-XED.txt +178 -0
  48. package/package.json +58 -4
@@ -0,0 +1,100 @@
1
+ // What the web page's bound view shows (web/js/bound.js), for the compact form (summarize(), the MCP `analyze` JSON):
2
+ // how busy each resource is as a share of the predicted cycles, the next limit after the bottleneck, the critical chain,
3
+ // and the instructions with the largest share of the binding resource. Derived from the response only (no analysis).
4
+ // tests-js/web_bound.mjs checks that it agrees with the page on the built-in examples.
5
+
6
+ import { caveats } from './web/caveats.js';
7
+
8
+ const FRONT = new Set(['MITE', 'MS', 'DSB', 'LSD']);
9
+ const COUNTS = new Set(['Issued', 'Exec.']);
10
+ const isPort = (c) => !FRONT.has(c) && !COUNTS.has(c);
11
+ const EPS = 0.005;
12
+ const SATURATED = 0.95;
13
+ const round = (x) => Math.round(x * 100) / 100;
14
+
15
+ const total = (r, i) => r.rows.reduce((s, x) => s + (Number(x.values?.[i]) || 0), 0);
16
+
17
+ // The weight of each row in a resource (as the page's blame()), or null.
18
+ function weights(r, id) {
19
+ const col = (name) => r.columns.indexOf(name);
20
+ const fromColumn = (i) => (i < 0 ? null : r.rows.map((x) => Number(x.values?.[i]) || 0));
21
+ if (id === 'Ports') {
22
+ const ports = r.columns.map((c, i) => ({ i, t: isPort(c) && c !== 'Div' ? total(r, i) : 0 })).filter((p) => p.t > 0);
23
+ if (!ports.length) return null;
24
+ const top = Math.max(...ports.map((p) => p.t));
25
+ const hot = ports.filter((p) => p.t >= SATURATED * top);
26
+ return { w: r.rows.map((x) => hot.reduce((s, p) => s + (Number(x.values?.[p.i]) || 0), 0)), ports: hot.map((p) => r.columns[p.i]) };
27
+ }
28
+ if (id === 'Issue') return { w: fromColumn(col('Issued')) };
29
+ if (FRONT.has(id)) return { w: fromColumn(col(id)) };
30
+ if (id === 'Decoder') {
31
+ const i = col('MITE');
32
+ if (i >= 0 && total(r, i) > 0) return { w: fromColumn(i) };
33
+ return { w: r.rows.map((x) => (x.kind === 'instr' && x.notes !== 'M' ? 1 : 0)) };
34
+ }
35
+ if (id === 'Predecoder') return { w: r.rows.map((x) => (x.kind === 'instr' ? String(x.opcode ?? '').length / 2 : 0)) };
36
+ if (id === 'Divider') return { w: fromColumn(col('Div')) };
37
+ if (id === 'Dependencies') {
38
+ const edges = r.criticalPath?.edges;
39
+ if (!Array.isArray(edges) || !edges.length) return null;
40
+ const w = r.rows.map(() => 0);
41
+ for (const e of edges) if (e.from >= 0 && e.from < w.length) w[e.from] += Number(e.latency) || 0;
42
+ return { w };
43
+ }
44
+ return null;
45
+ }
46
+
47
+ // {utilization, binding, largest?, next?, unexplained?, chain?, hot?} or null.
48
+ // utilization: {limit or port column: cycles / tp} (1 = busy every cycle; above 1: uiCA's bound is above the simulation)
49
+ // binding: the bottleneck(s) uiCA names (the response's `bottlenecks`; [] when it names none: no single limit explains
50
+ // tp, the page says "unknown")
51
+ // largest: when uiCA names none, the largest limit(s): the nearest bound, which alone does not reach tp
52
+ // next: {limit, tp, maxSpeedup}: the largest limit below the binding one; tp / next.tp is an upper bound of the speedup
53
+ // unexplained: cycles per iteration that no single limit explains
54
+ // chain: the critical loop-carried chain: [{index, instr, operand, latency, carried}] (index into `instructions`)
55
+ // hot: {resource, ports?, instructions: [{index, instr, share}]}: the largest shares of the binding resource (top 5)
56
+ // caveats: [{id, text, title, instructions: [index]}]: known blind spots the block meets (web/js/caveats.js):
57
+ // rmw-index (store forwarding between iterations through an indexed address), exit (an exit's mispredict),
58
+ // split (loads that may cross a cache line; on a CPU whose model charges crossings, only the loads it cannot
59
+ // follow); absent if none
60
+ // config: the CPU's configuration in uarch.json (configs[r.arch]), for the caveats; without it, split warns as on a CPU
61
+ // without a split-load cost (the instance's insights() and summarize() pass it).
62
+ export function insights(r, config = null) {
63
+ const tp = Number(r?.tp);
64
+ if (!(tp > 0) || !Array.isArray(r.limits) || !Array.isArray(r.rows) || !Array.isArray(r.columns)) return null;
65
+ const utilization = {};
66
+ for (const l of r.limits) utilization[l.name] = round(l.tp / tp);
67
+ r.columns.forEach((c, i) => { if (isPort(c)) { const t = total(r, i); if (t > 0) utilization[c] = round(t / tp); } });
68
+ const limits = r.limits.map((l) => ({ name: l.name, tp: Number(l.tp) }));
69
+ const max = limits.length ? Math.max(...limits.map((l) => l.tp)) : 0;
70
+ // the cycles of a bottleneck: its limit; the divider (no limit of its own): the Div column
71
+ const divCol = r.columns.indexOf('Div');
72
+ const valueOf = (name) => limits.find((l) => l.name === name)?.tp ?? (name === 'Divider' && divCol >= 0 ? total(r, divCol) : 0);
73
+ const binding = [...(r.bottlenecks ?? [])];
74
+ const largest = binding.length ? [] : limits.filter((l) => l.tp >= max - EPS).map((l) => l.name);
75
+ const top = binding.length ? binding : largest;
76
+ const bindValue = Math.max(0, ...top.map(valueOf));
77
+ let next = null;
78
+ for (const l of limits) if (!top.includes(l.name) && l.tp < bindValue - EPS && (!next || l.tp > next.tp)) next = { limit: l.name, tp: l.tp };
79
+ const out = { utilization, binding };
80
+ if (largest.length) out.largest = largest;
81
+ if (next) out.next = { ...next, maxSpeedup: next.tp > 0 ? round(tp / next.tp) : null };
82
+ if (limits.length && tp - max > EPS) out.unexplained = round(tp - max);
83
+ const edges = r.criticalPath?.edges;
84
+ if (Array.isArray(edges) && edges.length) {
85
+ out.chain = edges.map((e) => ({ index: e.from, instr: r.rows[e.from]?.label, operand: String(e.operand).toLowerCase(), latency: e.latency, carried: !!e.carried }));
86
+ }
87
+ if (top[0]) {
88
+ const b = weights(r, top[0]);
89
+ const sum = b?.w?.reduce((s, x) => s + x, 0) ?? 0;
90
+ if (b?.w && sum > 0) {
91
+ const shares = b.w.map((x, index) => ({ index, share: x / sum })).filter((x) => x.share > 0)
92
+ .sort((a, c) => c.share - a.share || a.index - c.index).slice(0, 5)
93
+ .map((x) => ({ index: x.index, instr: r.rows[x.index].label, share: round(x.share) }));
94
+ out.hot = { resource: top[0], ...(b.ports ? { ports: b.ports } : {}), instructions: shares };
95
+ }
96
+ }
97
+ const cv = caveats(r, config);
98
+ if (cv.length) out.caveats = cv.map((c) => ({ id: c.id, text: c.text, title: c.title, instructions: c.rows }));
99
+ return out;
100
+ }
package/lib/mcp.js ADDED
@@ -0,0 +1,366 @@
1
+ // The MCP tools of wuica as plain data (one definition for the stdio server here and the HTTP server in server/): name,
2
+ // title, description, input JSON Schema, annotations and the handler; a small JSON Schema validator for exactly the
3
+ // keywords these schemas use; and the stdio server (`wuica mcp`, `wuica-mcp`): newline-delimited JSON-RPC 2.0 on
4
+ // stdin/stdout, no dependencies. stdout carries protocol messages only.
5
+ //
6
+ // Protocol: the initialize handshake of the MCP revisions 2025-11-25, 2025-06-18, 2025-03-26 and 2024-11-05 (the
7
+ // client's version if it is one of these, else the latest); ping; tools/list; tools/call. JSON-RPC batches (arrays) only
8
+ // under 2025-03-26, the one revision that has them. Notifications get no reply. The process ends at the end of stdin.
9
+
10
+ import fs from 'node:fs';
11
+ import readline from 'node:readline';
12
+ import { createWuica } from './index.js';
13
+ import { whatIf, VARIANTS } from './whatif.js';
14
+
15
+ const pkg = JSON.parse(fs.readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
16
+
17
+ export const PROTOCOL_VERSIONS = Object.freeze(['2025-11-25', '2025-06-18', '2025-03-26', '2024-11-05']);
18
+ export const SERVER_INFO = Object.freeze({ name: 'wuica', version: pkg.version });
19
+ export const CAPABILITIES = Object.freeze({ tools: { listChanged: true } });
20
+
21
+ const ASSUMPTIONS =
22
+ 'The number is the predicted steady-state throughput in core clock cycles per iteration of the block: a block that ends ' +
23
+ 'with a (conditional) branch is simulated as a loop body; any other block as if it were unrolled, i.e. repeated back to ' +
24
+ 'back. Lower is faster. Assumptions: all memory accesses hit the L1 data cache, no branch mispredictions, no ' +
25
+ 'interference from other code or hyperthreads; the result does not depend on register or memory values except through ' +
26
+ 'dependencies. ZEN3, ADL-P and ICX are prototype models (experimental, from the fork jtl06/uiCA), less validated than ' +
27
+ "uiCA's Intel models (SNB through RKL).";
28
+
29
+ const INPUT_NOTE =
30
+ 'Give the block either as `source` (x86-64 assembly in Intel (noprefix) or AT&T syntax: detected unless `syntax` says; one instruction per ' +
31
+ 'line; labels and directives are allowed, e.g. "loop: add rax, [rsi]\\n dec rcx\\n jnz loop") or as `hex` (machine ' +
32
+ 'code bytes, e.g. "4801d8"). A whole function (gcc -S or clang -S output, objdump -d lines with addresses, with or ' +
33
+ 'without the bytes) is fine: by default (`loop: "auto"`) its innermost loop is analyzed (the first one in the code), ' +
34
+ 'or the body without prologue and epilogue if it is a compiler\'s function without a loop; the deepest loop is ' +
35
+ 'preferred (clang\'s "Inner Loop Header" notes count), among equals the first; branches out of the loop count as not taken (so an exit ' +
36
+ 'to a label that is not in the text assembles); with addresses, the alignment offset is the loop\'s address mod 64 ' +
37
+ 'unless options.alignmentOffset is given. The response\'s `loop` says what was analyzed (index, count, name, lines, ' +
38
+ 'address, function, depth). `loop: "whole"` analyzes the whole text; `loop: N` the N-th loop (0-based: deepest first, ' +
39
+ 'then in code order); `loop: ".LBB0_12"` a loop by its label; `func: "name"` only the loops of that function.';
40
+
41
+ const ERRORS_NOTE =
42
+ 'Failures are tool errors whose JSON is {code, error, stderr}: code 1 = bad request (e.g. unknown arch, bad hex), ' +
43
+ '2 = assembler error (stderr lines as llvm-mc prints them; positioned ones carry tag {line, column, severity, text}), ' +
44
+ '3 = the analysis failed for this input.';
45
+
46
+ // ---- the input schemas (JSON Schema, draft-07 as before) ----------------------------------------------------------------
47
+
48
+ const SCHEMA = 'http://json-schema.org/draft-07/schema#';
49
+ const obj = (properties, required = []) => ({ type: 'object', properties, ...(required.length ? { required } : {}), $schema: SCHEMA, additionalProperties: false });
50
+ const str = (description, extra = {}) => ({ description, type: 'string', ...extra });
51
+
52
+ const codeShape = {
53
+ source: str('x86-64 assembly text of the basic block (give source or hex)'),
54
+ hex: str('machine code as hex bytes, e.g. "4801d84801c349ffcf75f5" (spaces allowed)'),
55
+ syntax: str('syntax of `source`: "auto" (default: detected from the text), "intel" (noprefix) or "att"', { enum: ['auto', 'intel', 'att'] }),
56
+ loop: {
57
+ description: 'what of `source` is analyzed: "auto" (default: the deepest loop of a whole function, else the text), "whole", the index of a loop (0-based), or its label',
58
+ anyOf: [{ type: 'string', enum: ['auto', 'whole'] }, { type: 'integer', minimum: 0, maximum: Number.MAX_SAFE_INTEGER }, { type: 'string', minLength: 1 }],
59
+ },
60
+ func: str('only the loops of this function (a label of `source`)', { minLength: 1 }),
61
+ };
62
+
63
+ const int = (description, minimum, maximum) => ({ description, type: 'integer', minimum, maximum });
64
+ const bool = (description) => ({ description, type: 'boolean' });
65
+ const optionsShape = {
66
+ description: 'simulation options of uiCA; all optional',
67
+ type: 'object',
68
+ properties: {
69
+ alignmentOffset: int('offset of the block from a 64-byte boundary (default 0); affects the front end', 0, 63),
70
+ initPolicy: str('initial register values: "diff" (default: all registers differ), "same", "stack"', { enum: ['diff', 'same', 'stack'] }),
71
+ simpleFrontEnd: bool('model a front end limited only by the issue width (default false)'),
72
+ noMicroFusion: bool('disable micro-fusion (default false)'),
73
+ noMacroFusion: bool('disable macro-fusion (default false)'),
74
+ minIterations: int('simulate at least this many iterations (default 10)', 1, 100000),
75
+ minCycles: int('simulate at least this many cycles (default 500)', 1, 1000000),
76
+ },
77
+ additionalProperties: false,
78
+ };
79
+
80
+ const json = (value) => ({ type: 'text', text: JSON.stringify(value, null, 1) });
81
+ const omitBytes = ({ bytes, ...rest }) => rest;
82
+
83
+ function result(r) {
84
+ return r.code ? { isError: true, content: [json(r)] } : { content: [json(r)] };
85
+ }
86
+
87
+ export const INSTRUCTIONS =
88
+ 'wuica predicts the throughput of x86-64 basic blocks (loop bodies) with uiCA\'s cycle-level pipeline model, ' +
89
+ 'locally. Use `analyze` for one block on one microarchitecture (bottlenecks, per-port usage, full report), ' +
90
+ '`what_if` for the effect of unrolling, an ideal front end, fusion, or removing the dependency chain, ' +
91
+ '`compare_archs` to see a block on several microarchitectures, `list_archs` for the ids, `assemble` to check ' +
92
+ 'that assembly text is accepted and see its encoding. ' + ASSUMPTIONS;
93
+
94
+ const readOnly = { readOnlyHint: true, idempotentHint: true, openWorldHint: false };
95
+ const execution = { taskSupport: 'forbidden' };
96
+
97
+ // The tools: [{name, title, description, inputSchema, annotations, execution, handler(args) -> CallToolResult}]. w: a
98
+ // wuica instance (createWuica) or anything with its analyze, compare, assemble, archs and summarize.
99
+ export function mcpTools(w) {
100
+ return [
101
+ {
102
+ name: 'list_archs',
103
+ title: 'List microarchitectures',
104
+ description:
105
+ 'Lists the microarchitecture models in order of release: id (to pass as `arch`), name, release year, and ' +
106
+ '`prototype` (true for the experimental models ZEN3, ADL-P and ICX of the fork jtl06/uiCA, which are less ' +
107
+ 'validated than uiCA\'s Intel models). `fields` selects fields (also available: table, xedChip).',
108
+ inputSchema: obj({
109
+ fields: { description: 'fields to return (default: id, name, year, prototype)', type: 'array', items: { type: 'string', enum: ['id', 'name', 'year', 'prototype', 'table', 'xedChip'] } },
110
+ }),
111
+ annotations: readOnly, execution,
112
+ handler: async ({ fields }) => ({ content: [json(w.archs(fields ?? ['id', 'name', 'year', 'prototype']))] }),
113
+ },
114
+ {
115
+ name: 'analyze',
116
+ title: 'Predict basic-block throughput (uiCA)',
117
+ description:
118
+ 'Simulates an x86-64 basic block on one microarchitecture with uiCA\'s pipeline model and returns the predicted ' +
119
+ 'throughput, the bottleneck(s), the per-component limits and a per-instruction table. ' + INPUT_NOTE + ' ' +
120
+ ASSUMPTIONS + '\n\nResult (JSON, format "json" or "both"): `tp` = cycles per iteration; `mode` = "loop" or ' +
121
+ '"unroll"; `bottlenecks` = the components that limit the throughput (e.g. Dependencies = a loop-carried ' +
122
+ 'dependency chain, Ports = execution-port pressure, Issue/Decoder/Predecoder/DSB/LSD = front end); `limits` = ' +
123
+ 'the throughput that would be achieved if that component were the only bottleneck (the largest is the binding ' +
124
+ 'one); `instructions[]` = per instruction: average uops per iteration issued/executed, `ports` = uops per ' +
125
+ 'iteration on each execution port, `uopSource` = where the uops came from (MITE legacy decoders, DSB uop cache, ' +
126
+ 'LSD loop buffer, MS microcode sequencer), `notes` M = macro-fused with the previous instruction, J = not ' +
127
+ 'cacheable in the DSB because of the JCC erratum, X = instruction not supported by the model (no data: the ' +
128
+ 'result is unreliable); `stderr` = assembler warnings and decode warnings (`decodeErrors` > 0: some bytes could ' +
129
+ 'not be decoded); `insights` = a derived diagnosis: `utilization` (each limit and execution port as a fraction ' +
130
+ 'of tp; 1 = saturated), `binding` (the limiting component: the same as `bottlenecks`; [] when uiCA names none, then ' +
131
+ '`largest` is the largest limit, the nearest bound, which alone does not reach tp), `next` (the next limit and `maxSpeedup`, an upper ' +
132
+ 'bound of the speedup if the binding component were removed), `unexplained` (cycles no single limit explains), ' +
133
+ '`chain` (the loop-carried critical dependency chain: `index` into `instructions`, operand, latency, carried ' +
134
+ 'into the next iteration), `hot` (the instructions with the largest share of the binding resource: fix these ' +
135
+ 'first), `caveats` (known blind spots of the model the block meets, not simulated: rmw-index = a read-modify-write ' +
136
+ 'to an indexed address, whose store forwarding between iterations depends on the data; exit = an exit before the ' +
137
+ 'loop\'s branch, whose mispredict is not modelled; split = loads at an offset that is not a multiple of their width, ' +
138
+ 'which may cross a cache line (on ZEN3, ADL-P and ICX, whose models charge crossings, only loads whose address register ' +
139
+ 'is written other than by adding an immediate); `instructions` = indexes into `instructions`). With `details: true`, each instruction also has `allowedPorts` (uops.info notation, e.g. 1*p0156+1*p23), ' +
140
+ '`uops`, `fusedUops`, `latencies` ("input->output:cycles"), `frontEnd` (length, offset = alignment offset + position in the block, crosses ' +
141
+ '16/32/64-byte boundaries, lcp = length-changing prefix, microcoded, macro-fusion), and `insights` has `portSet` (the ' +
142
+ 'ports behind the Ports limit and the instructions whose uops can only use them) and `issueSlots` (issue slots per ' +
143
+ 'iteration: issued, or lost to the front end, a full reorder buffer (rob) or scheduler (rs), other). ' +
144
+ 'Format "text" (or the second item of "both") is uiCA\'s complete text report. ' + ERRORS_NOTE,
145
+ inputSchema: obj({
146
+ arch: str('microarchitecture id (default "SKL"); see list_archs, e.g. SKL, ICL, TGL, RKL, ADL-P, ZEN3'),
147
+ ...codeShape,
148
+ options: optionsShape,
149
+ format: str('"json" (summary), "text" (uiCA\'s report) or "both" (default)', { enum: ['json', 'text', 'both'] }),
150
+ details: bool('true: per instruction also its allowed ports, latencies and front-end facts, and in insights the port set behind the Ports limit and the issue slots per cause (a slower analysis; default false)'),
151
+ }),
152
+ annotations: readOnly, execution,
153
+ handler: async ({ arch, format, details, ...request }) => {
154
+ const r = await w.analyze(arch ?? 'SKL', details ? { ...request, options: { ...(request.options ?? {}), details: true } } : request);
155
+ if (r.code) return result(r);
156
+ const content = [];
157
+ if (format !== 'text') content.push(json(w.summarize(r)));
158
+ if (format !== 'json') content.push({ type: 'text', text: r.text });
159
+ return { content };
160
+ },
161
+ },
162
+ {
163
+ name: 'what_if',
164
+ title: 'What-if experiments on a basic block',
165
+ description:
166
+ 'Re-analyzes an x86-64 basic block with one change each and reports the predicted throughput per ORIGINAL ' +
167
+ 'iteration, the change `delta` (cycles; negative = faster) and `speedup` (base tp / variant tp) against the base: ' +
168
+ 'unroll2/unroll4/unroll8 (n copies of the loop body and its branch once; registers are not renamed, so the ' +
169
+ 'dependencies stay and only the loop overhead goes; loops only), acc2/acc3/acc4/acc8 (N accumulators: unrolled ×N ' +
170
+ 'with the register of the loop-carried chain renamed into a free register in each copy, so the copies form N ' +
171
+ 'independent chains, as N accumulators or N CRC streams written by hand; `renamed` says which registers; the ' +
172
+ 'result\'s `accumulators.best` is the smallest N within 1% of the fastest, 1 = as it is: call it per arch for the ' +
173
+ 'best N per CPU; not possible when the chain goes through memory or flags or an implicit operand), simpleFrontEnd (a front end limited only by the ' +
174
+ 'issue width), noMacroFusion / noMicroFusion (switched; if the base already has the option set, the variant ' +
175
+ 'switches it back), nochain (no analysis: the largest limit other than Dependencies, an estimate of the ' +
176
+ 'throughput without the loop-carried chain; `estimate: true`). A variant that cannot be made or analyzed has ' +
177
+ '`error`. Use it to decide whether unrolling, breaking the chain or front-end work is worth it. ' + INPUT_NOTE + ' ' +
178
+ ASSUMPTIONS + ' ' + ERRORS_NOTE,
179
+ inputSchema: obj({
180
+ arch: str('microarchitecture id (default "SKL"); see list_archs'),
181
+ ...codeShape,
182
+ options: optionsShape,
183
+ variants: { description: `the experiments (default: all of ${VARIANTS.join(', ')})`, type: 'array', items: { type: 'string', enum: [...VARIANTS] } },
184
+ }),
185
+ annotations: readOnly, execution,
186
+ handler: async ({ arch, variants, ...request }) => result(await whatIf((a, req) => w.analyze(a, req), arch ?? 'SKL', request, variants ?? VARIANTS, { assemble: (text) => w.assemble(text, 'intel') })),
187
+ },
188
+ {
189
+ name: 'compare_archs',
190
+ title: 'Compare a block across microarchitectures',
191
+ description:
192
+ 'Predicts the throughput of one x86-64 basic block on several microarchitectures (default: all) and returns, per ' +
193
+ 'microarchitecture, `tp` in cycles per iteration and the bottleneck(s) (a row with code != 0 failed on that ' +
194
+ 'microarchitecture). Use it to see how a loop behaves on older vs. newer Intel cores or on AMD Zen 3. ' +
195
+ INPUT_NOTE + ' ' + ASSUMPTIONS + ' ' + ERRORS_NOTE,
196
+ inputSchema: obj({
197
+ ...codeShape,
198
+ archs: { description: 'microarchitecture ids to compare (default: all of list_archs)', type: 'array', items: { type: 'string' } },
199
+ options: optionsShape,
200
+ }),
201
+ annotations: readOnly, execution,
202
+ handler: async (request) => result(await w.compare(request)),
203
+ },
204
+ {
205
+ name: 'assemble',
206
+ title: 'Assemble x86-64 code',
207
+ description:
208
+ 'Assembles x86-64 assembly text with LLVM\'s assembler (LLVM 22, the same bytes as llvm-mc) and returns ' +
209
+ '{code: 0, hex, length, stderr} (stderr: warnings), or the assembler\'s errors as {code: 2, error, stderr} with ' +
210
+ 'line/column tags. The syntax is detected unless given (Intel noprefix or AT&T); the text may switch with .intel_syntax noprefix / ' +
211
+ '.att_syntax. Only .text is returned.',
212
+ inputSchema: obj({
213
+ source: { description: 'the assembly text', type: 'string' },
214
+ syntax: codeShape.syntax,
215
+ }, ['source']),
216
+ annotations: readOnly, execution,
217
+ handler: async ({ source, syntax }) => result(omitBytes(await w.assemble(source, syntax ?? 'auto'))),
218
+ },
219
+ ];
220
+ }
221
+
222
+ // The tool as tools/list shows it (without the handler).
223
+ export const toolListing = ({ handler, ...t }) => t;
224
+
225
+ // ---- a validator for the keywords these schemas use ------------------------------------------------------------------------
226
+ // type (object, array, string, integer, number, boolean), properties, required, additionalProperties: false, enum, items,
227
+ // minimum, maximum, minLength, anyOf. Returns the first problem as text ("options.minIterations: expected an integer,
228
+ // got \"many\""), or null.
229
+ const kind = (v) => (v === null ? 'null' : Array.isArray(v) ? 'an array' : typeof v === 'object' ? 'an object' : typeof v === 'string' ? 'a string' : typeof v === 'boolean' ? 'a boolean' : typeof v === 'number' ? (Number.isInteger(v) ? 'an integer' : 'a number') : typeof v);
230
+ const show = (v) => JSON.stringify(v)?.slice(0, 60) ?? String(v);
231
+ export function validate(schema, value, at = '') {
232
+ const where = at || 'arguments';
233
+ if (schema.anyOf) {
234
+ const errs = schema.anyOf.map((s) => validate(s, value, at));
235
+ if (errs.some((e) => e === null)) return null;
236
+ const allowed = schema.anyOf.map((s) => (s.enum ? s.enum.map((x) => JSON.stringify(x)).join(' or ') : s.type === 'integer' ? `an integer${s.minimum !== undefined ? ` >= ${s.minimum}` : ''}` : s.minLength ? 'a non-empty string' : `a ${s.type}`));
237
+ return `${where}: expected ${allowed.join(', or ')}, got ${show(value)}`;
238
+ }
239
+ switch (schema.type) {
240
+ case 'object': {
241
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) return `${where}: expected an object, got ${kind(value)}`;
242
+ for (const k of schema.required ?? []) if (!(k in value) || value[k] === undefined) return `${at ? `${at}.` : ''}${k}: required`;
243
+ const props = schema.properties ?? {};
244
+ if (schema.additionalProperties === false) {
245
+ const extra = Object.keys(value).filter((k) => !Object.hasOwn(props, k));
246
+ if (extra.length) return `${where}: unknown key${extra.length > 1 ? 's' : ''} ${extra.map((k) => JSON.stringify(k)).join(', ')} (known: ${Object.keys(props).join(', ')})`;
247
+ }
248
+ for (const [k, s] of Object.entries(props)) {
249
+ if (value[k] === undefined) continue;
250
+ const e = validate(s, value[k], at ? `${at}.${k}` : k);
251
+ if (e) return e;
252
+ }
253
+ return null;
254
+ }
255
+ case 'array': {
256
+ if (!Array.isArray(value)) return `${where}: expected an array, got ${kind(value)}`;
257
+ for (let i = 0; i < value.length; i++) { const e = schema.items ? validate(schema.items, value[i], `${where}[${i}]`) : null; if (e) return e; }
258
+ return null;
259
+ }
260
+ case 'string':
261
+ if (typeof value !== 'string') return `${where}: expected a string, got ${kind(value)}`;
262
+ if (schema.minLength !== undefined && value.length < schema.minLength) return `${where}: expected at least ${schema.minLength} character${schema.minLength === 1 ? '' : 's'}`;
263
+ break;
264
+ case 'integer':
265
+ if (!Number.isInteger(value)) return `${where}: expected an integer, got ${show(value)}`;
266
+ break;
267
+ case 'number':
268
+ if (typeof value !== 'number' || !Number.isFinite(value)) return `${where}: expected a number, got ${show(value)}`;
269
+ break;
270
+ case 'boolean':
271
+ if (typeof value !== 'boolean') return `${where}: expected true or false, got ${show(value)}`;
272
+ break;
273
+ default:
274
+ break;
275
+ }
276
+ if (schema.enum && !schema.enum.includes(value)) return `${where}: expected one of ${schema.enum.map((x) => JSON.stringify(x)).join(', ')}, got ${show(value)}`;
277
+ if (schema.minimum !== undefined && value < schema.minimum) return `${where}: expected at least ${schema.minimum}, got ${value}`;
278
+ if (schema.maximum !== undefined && value > schema.maximum) return `${where}: expected at most ${schema.maximum}, got ${value}`;
279
+ return null;
280
+ }
281
+
282
+ // tools/call on a table of tools: a CallToolResult, or {error: {code, message}} for a protocol error (an unknown tool).
283
+ // Arguments that do not fit the schema are a tool error (isError), as the MCP specification asks, so a model can retry.
284
+ export async function callTool(tools, name, args) {
285
+ const tool = tools.find((t) => t.name === name);
286
+ if (!tool) return { error: { code: -32602, message: `Unknown tool: ${name}` } };
287
+ const problem = validate(tool.inputSchema, args ?? {});
288
+ if (problem) return { isError: true, content: [{ type: 'text', text: `Invalid arguments for tool ${name}: ${problem}` }] };
289
+ try {
290
+ return await tool.handler(args ?? {});
291
+ } catch (e) {
292
+ return { isError: true, content: [{ type: 'text', text: `${name} failed: ${e?.message ?? e}` }] };
293
+ }
294
+ }
295
+
296
+ // ---- the stdio server ----------------------------------------------------------------------------------------------------------
297
+
298
+ const RPC = { parse: -32700, invalidRequest: -32600, method: -32601, params: -32602, internal: -32603 };
299
+ const err = (id, code, message) => ({ jsonrpc: '2.0', id: id ?? null, error: { code, message } });
300
+ const ok = (id, result) => ({ jsonrpc: '2.0', id, result });
301
+
302
+ // One JSON-RPC message (an object) -> the reply object, or null (a notification, or a response from the client).
303
+ export async function handleMessage(state, tools, m) {
304
+ if (m === null || typeof m !== 'object' || Array.isArray(m) || m.jsonrpc !== '2.0') return err(m?.id, RPC.invalidRequest, 'Invalid Request: not a JSON-RPC 2.0 message');
305
+ const isRequest = 'id' in m && m.id !== null && (typeof m.id === 'string' || typeof m.id === 'number');
306
+ if (typeof m.method !== 'string') {
307
+ if ('result' in m || 'error' in m) return null; // a response (this server sends no requests)
308
+ return err(m.id, RPC.invalidRequest, 'Invalid Request: no method');
309
+ }
310
+ if (!isRequest) {
311
+ if ('id' in m) return err(null, RPC.invalidRequest, 'Invalid Request: the id must be a string or a number');
312
+ return null; // notifications/initialized, notifications/cancelled, ...: nothing to answer
313
+ }
314
+ const params = m.params ?? {};
315
+ if (params === null || typeof params !== 'object') return err(m.id, RPC.params, 'Invalid params: expected an object');
316
+ switch (m.method) {
317
+ case 'initialize': {
318
+ if (typeof params.protocolVersion !== 'string') return err(m.id, RPC.params, 'Invalid params: protocolVersion (a string) is required');
319
+ state.version = PROTOCOL_VERSIONS.includes(params.protocolVersion) ? params.protocolVersion : PROTOCOL_VERSIONS[0];
320
+ return ok(m.id, { protocolVersion: state.version, capabilities: CAPABILITIES, serverInfo: SERVER_INFO, instructions: INSTRUCTIONS });
321
+ }
322
+ case 'ping':
323
+ return ok(m.id, {});
324
+ case 'tools/list':
325
+ return ok(m.id, { tools: tools.map(toolListing) });
326
+ case 'tools/call': {
327
+ if (typeof params.name !== 'string') return err(m.id, RPC.params, 'Invalid params: name (a string) is required');
328
+ if (params.arguments !== undefined && (params.arguments === null || typeof params.arguments !== 'object' || Array.isArray(params.arguments))) return err(m.id, RPC.params, 'Invalid params: arguments must be an object');
329
+ const r = await callTool(tools, params.name, params.arguments);
330
+ return r.error ? err(m.id, r.error.code, r.error.message) : ok(m.id, r);
331
+ }
332
+ default:
333
+ return err(m.id, RPC.method, `Method not found: ${m.method}`);
334
+ }
335
+ }
336
+
337
+ // One line of input -> the line to write, or null.
338
+ export async function handleLine(state, tools, line) {
339
+ if (!line.trim()) return null;
340
+ let m;
341
+ try { m = JSON.parse(line); } catch { return JSON.stringify(err(null, RPC.parse, 'Parse error')); }
342
+ if (Array.isArray(m)) {
343
+ // batches: only the 2025-03-26 revision has them
344
+ if (state.version !== '2025-03-26') return JSON.stringify(err(null, RPC.invalidRequest, 'Invalid Request: batches are not supported in this protocol version'));
345
+ if (!m.length) return JSON.stringify(err(null, RPC.invalidRequest, 'Invalid Request: an empty batch'));
346
+ const replies = (await Promise.all(m.map((x) => handleMessage(state, tools, x)))).filter(Boolean);
347
+ return replies.length ? JSON.stringify(replies) : null;
348
+ }
349
+ const r = await handleMessage(state, tools, m);
350
+ return r ? JSON.stringify(r) : null;
351
+ }
352
+
353
+ // The stdio server: requests are answered in the order they arrive; the end of stdin ends it.
354
+ export async function runServer(options = {}, io = { stdin: process.stdin, stdout: process.stdout }) {
355
+ const w = await createWuica(options);
356
+ const tools = mcpTools(w);
357
+ const state = { version: null };
358
+ // a client that closes its end early: the writes that follow are dropped, the end of stdin still ends the server
359
+ io.stdout.on?.('error', (e) => { if (e?.code !== 'EPIPE') throw e; });
360
+ const rl = readline.createInterface({ input: io.stdin, crlfDelay: Infinity });
361
+ for await (const line of rl) {
362
+ const out = await handleLine(state, tools, line);
363
+ if (out !== null) io.stdout.write(out + '\n');
364
+ }
365
+ await w.close?.();
366
+ }