-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcodegen.mts
More file actions
1138 lines (981 loc) · 45.4 KB
/
Copy pathcodegen.mts
File metadata and controls
1138 lines (981 loc) · 45.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* FAFOaaS polyglot codegen — one run, three languages, contract tests included.
*
* Sources (in order of authority):
* - spec/mcp/schema.ts imported DIRECTLY (tsx) — constants, annotations,
* error codes flow by execution, not by parsing.
* - spec/mcp/schema.json model shapes → quicktype → Go / Python / TypeScript.
* - dist/asyncapi.bundle.yaml channel addresses, Kafka topics, contract version,
* and the canonical message examples.
*
* Contract tests are DERIVED, not written: the AsyncAPI examples become valid
* vectors; systematic mutations against schema.json constraints (required /
* enum / type / bounds) become invalid vectors. One vectors.json, three
* generated harnesses. Add a field to the spec and new test cases appear in
* every language on the next run.
*
* Output: gen/{go,python,typescript}/fafo — self-contained per language.
* Hand-editing generated code is `category: other`, `recklessness: 8`, and
* the validate gate is your findout channel.
*/
import { execFileSync } from "node:child_process";
import { mkdirSync, readFileSync, writeFileSync, rmSync } from "node:fs";
import * as yaml from "js-yaml";
import * as schema from "../spec/mcp/schema.ts";
const OUT = { go: "gen/go/fafo", py: "gen/python/fafo", ts: "gen/typescript/fafo" };
const HEADER = "GENERATED by scripts/codegen.mts from spec/mcp/schema.ts + spec/asyncapi.yaml. DO NOT EDIT.";
/* ---------------------------------------------------------------- inputs */
const bundle = yaml.load(readFileSync("dist/asyncapi.bundle.yaml", "utf8")) as any;
const jsonSchema = JSON.parse(readFileSync("spec/mcp/schema.json", "utf8"));
const contractVersion: string = bundle.info.version;
const channels: Record<string, { address: string; topic?: string }> = {};
for (const [name, ch] of Object.entries<any>(bundle.channels)) {
channels[name] = { address: ch.address, topic: ch.bindings?.kafka?.topic };
}
const errorCodes: Record<string, number> = {};
for (const [k, v] of Object.entries(schema.FafoErrorCode)) {
if (typeof v === "number") errorCodes[k] = v;
}
const toolNames = Object.keys(schema.FAFO_TOOL_ANNOTATIONS) as schema.FafoToolName[];
/* --------------------------------------------------- quicktype models */
// quicktype prefers enum form over `const` (a bare boolean/string const
// crashes its renderers). Normalize const → single-value enum in the copy we
// feed it; the canonical schema.json is not touched.
function constToEnum(node: any): any {
if (Array.isArray(node)) return node.map(constToEnum);
if (node && typeof node === "object") {
const out: any = {};
for (const [k, v] of Object.entries(node)) {
if (k === "const") out.enum = [v];
else out[k] = constToEnum(v);
}
return out;
}
return node;
}
// schema.json is definitions-only; quicktype needs a root. Synthesize one
// property per definition so every type is reachable and generated.
const rooted = {
...constToEnum(jsonSchema),
title: "FafoSchema",
type: "object",
additionalProperties: false,
properties: Object.fromEntries(
Object.keys(jsonSchema.definitions).map((d) => [d, { $ref: `#/definitions/${d}` }]),
),
};
const rootedPath = "dist/schema.rooted.json";
writeFileSync(rootedPath, JSON.stringify(rooted, null, 2));
function quicktype(lang: string, out: string, extra: string[] = []) {
execFileSync(
"npx",
["quicktype", "-s", "schema", rootedPath, "--lang", lang, "-o", out,
"--top-level", "FafoSchema", ...extra],
{ stdio: "inherit" },
);
}
for (const dir of Object.values(OUT)) {
rmSync(dir, { recursive: true, force: true });
mkdirSync(dir, { recursive: true });
}
quicktype("go", `${OUT.go}/models.go`, ["--package", "fafo"]);
quicktype("python", `${OUT.py}/models.py`, ["--python-version", "3.7"]);
quicktype("typescript", `${OUT.ts}/models.ts`, ["--prefer-unions", "--prefer-const-values"]);
/* ------------------------------------------------ contract test vectors */
type VectorKind = "valid" | "required" | "enum" | "type" | "bounds";
interface Vector {
id: string;
schema: string;
kind: VectorKind;
payload: unknown;
note?: string;
}
// Payload schema → the AsyncAPI message whose examples exercise it.
const EXAMPLE_SOURCES: Record<string, string> = {
Intent: "IntentDeclared",
Escalation: "AroundEscalated",
Warning: "WarningIssued",
Consequence: "ConsequenceMaterialized",
Lesson: "LessonRecorded",
FoaasMessage: "ToldYouSoBroadcast",
};
const deref = (node: any): any =>
node?.$ref ? jsonSchema.definitions[node.$ref.split("/").pop()] : node;
const wrongTypeValue = (prop: any): unknown => {
const t = prop.type ?? (prop.enum ? typeof prop.enum[0] : undefined);
switch (t) {
case "string": return 42;
case "integer":
case "number": return "eleven"; // the scale goes to eleven, not to "eleven"
case "boolean": return "maybe";
case "array": return "not_an_array";
case "object": return "not_an_object";
default: return undefined;
}
};
const vectors: Vector[] = [];
for (const [schemaName, msgName] of Object.entries(EXAMPLE_SOURCES)) {
const msg = bundle.components.messages[msgName];
const def = jsonSchema.definitions[schemaName];
const examples: any[] = msg.examples ?? [];
if (!examples.length) throw new Error(`${msgName}: no examples in the contract — cannot derive vectors`);
for (const ex of examples) {
vectors.push({ id: `${schemaName}.valid.${ex.name}`, schema: schemaName, kind: "valid", payload: ex.payload });
}
const base = examples[0].payload;
for (const req of def.required ?? []) {
const p = { ...base };
delete p[req];
vectors.push({ id: `${schemaName}.required.${req}`, schema: schemaName, kind: "required", payload: p, note: `missing required '${req}'` });
}
for (const [prop, raw] of Object.entries<any>(def.properties ?? {})) {
const ps = deref(raw);
if (ps.enum && typeof ps.enum[0] === "string") {
vectors.push({ id: `${schemaName}.enum.${prop}`, schema: schemaName, kind: "enum", payload: { ...base, [prop]: "___jaywalking___" }, note: `'${prop}' outside its enum` });
}
const wrong = wrongTypeValue(ps);
if (wrong !== undefined) {
vectors.push({ id: `${schemaName}.type.${prop}`, schema: schemaName, kind: "type", payload: { ...base, [prop]: wrong }, note: `'${prop}' with wrong JSON type` });
}
if (typeof ps.maximum === "number") {
vectors.push({ id: `${schemaName}.bounds.${prop}.max`, schema: schemaName, kind: "bounds", payload: { ...base, [prop]: ps.maximum + 1 }, note: `'${prop}' > ${ps.maximum}` });
} else if (typeof ps.minimum === "number") {
vectors.push({ id: `${schemaName}.bounds.${prop}.min`, schema: schemaName, kind: "bounds", payload: { ...base, [prop]: ps.minimum - 1 }, note: `'${prop}' < ${ps.minimum}` });
}
}
}
const vectorFile = JSON.stringify(
{ contractVersion, note: HEADER, vectors },
null,
2,
);
// Identical copy in each package: every client is self-contained.
writeFileSync(`${OUT.go}/vectors.json`, vectorFile);
writeFileSync(`${OUT.py}/vectors.json`, vectorFile);
writeFileSync(`${OUT.ts}/vectors.json`, vectorFile);
const counts = vectors.reduce<Record<string, number>>((acc, v) => ((acc[v.kind] = (acc[v.kind] ?? 0) + 1), acc), {});
/* --------------------------------------------------- contract emitters */
const upperSnake = (s: string) => s.replace(/([a-z0-9])([A-Z])/g, "$1_$2").toUpperCase();
const goStr = (s: string) => JSON.stringify(s);
const mapLines = (obj: Record<string, string | undefined>, fmt: (k: string, v: string) => string) =>
Object.entries(obj).filter(([, v]) => v !== undefined).map(([k, v]) => fmt(k, v!)).join("\n");
/* ----- Go ----- */
const goAnn = toolNames
.map((t) => {
const a = schema.FAFO_TOOL_ANNOTATIONS[t];
return `\t"${t}": {ReadOnlyHint: ${a.readOnlyHint}, DestructiveHint: ${a.destructiveHint}, IdempotentHint: ${a.idempotentHint}, OpenWorldHint: ${a.openWorldHint}},`;
})
.join("\n");
writeFileSync(
`${OUT.go}/contract.go`,
`// Code generated by scripts/codegen.mts. DO NOT EDIT.
// ${HEADER}
package fafo
// Contract identity.
const (
\tContractVersion = ${goStr(contractVersion)}
\tFafoMCPVersion = ${goStr(schema.FAFO_MCP_VERSION)}
\tMCPProtocolVersion = ${goStr(schema.MCP_PROTOCOL_VERSION)}
\tFafoURIScheme = ${goStr(schema.FAFO_URI_SCHEME)}
)
// FafoErrorCode is a fafo-mcp JSON-RPC error code. Consequences are non-appealable.
type FafoErrorCode int
const (
${Object.entries(errorCodes).map(([k, v]) => `\tErr${k} FafoErrorCode = ${v}`).join("\n")}
)
// ChannelAddresses maps channel name to its AsyncAPI address (RFC 6570 level 1).
var ChannelAddresses = map[string]string{
${mapLines(Object.fromEntries(Object.entries(channels).map(([k, v]) => [k, v.address])), (k, v) => `\t"${k}": ${goStr(v)},`)}
}
// KafkaTopics maps channel name to its Kafka topic on the Causality Fabric.
var KafkaTopics = map[string]string{
${mapLines(Object.fromEntries(Object.entries(channels).map(([k, v]) => [k, v.topic])), (k, v) => `\t"${k}": ${goStr(v)},`)}
}
// ResourceTemplates is the fafo-mcp resource URI surface (binding rule B2/B4).
var ResourceTemplates = map[string]string{
${mapLines(schema.FAFO_RESOURCE_TEMPLATES as Record<string, string>, (k, v) => `\t"${k}": ${goStr(v)},`)}
}
// ToolAnnotations are the normative MCP tool annotations (FAFO-MCP §5).
type ToolAnnotations struct {
\tReadOnlyHint bool
\tDestructiveHint bool
\tIdempotentHint bool
\tOpenWorldHint bool
}
// FafoToolAnnotations: fuck_around is destructive because it is.
var FafoToolAnnotations = map[string]ToolAnnotations{
${goAnn}
}
// ToolNames is the complete, closed set of ways to fuck around.
var ToolNames = []string{${toolNames.map((t) => `"${t}"`).join(", ")}}
`,
);
writeFileSync(
`${OUT.go}/go.mod`,
`// ${HEADER}
module github.com/zuub-don/fafoaas/gen/go/fafo
go 1.24
`,
);
/* ----- Go contract tests ----- */
const goDispatch = Object.keys(EXAMPLE_SOURCES)
.map(
(s) => `\tcase "${s}":
\t\tvar v ${s}
\t\tif err := json.Unmarshal(payload, &v); err != nil {
\t\t\treturn nil, err
\t\t}
\t\treturn json.Marshal(v)`,
)
.join("\n");
writeFileSync(
`${OUT.go}/contract_test.go`,
`// Code generated by scripts/codegen.mts. DO NOT EDIT.
// Contract tests derived from the FAFOaaS specs: valid vectors are the
// AsyncAPI message examples; invalid vectors are systematic mutations
// against spec/mcp/schema.json constraints.
//
// enforcedKinds documents this client's validation envelope: encoding/json
// rejects JSON type violations only. Enum, required, and bounds violations
// pass through — Go finds out at a different layer. If quicktype ever grows
// stricter Go validation, widen the set and the vectors are already waiting.
package fafo
import (
\t_ "embed"
\t"encoding/json"
\t"reflect"
\t"testing"
)
//go:embed vectors.json
var vectorsJSON []byte
type vector struct {
\tID string \`json:"id"\`
\tSchema string \`json:"schema"\`
\tKind string \`json:"kind"\`
\tPayload json.RawMessage \`json:"payload"\`
}
var enforcedKinds = map[string]bool{"type": true}
func roundTrip(schema string, payload []byte) ([]byte, error) {
\tswitch schema {
${goDispatch}
\t}
\treturn nil, nil
}
func TestContractVectors(t *testing.T) {
\tvar doc struct {
\t\tVectors []vector \`json:"vectors"\`
\t}
\tif err := json.Unmarshal(vectorsJSON, &doc); err != nil {
\t\tt.Fatalf("vectors.json unreadable: %v", err)
\t}
\tvalid, rejected, skipped := 0, 0, 0
\tfor _, vec := range doc.Vectors {
\t\tvec := vec
\t\tt.Run(vec.ID, func(t *testing.T) {
\t\t\tout, err := roundTrip(vec.Schema, vec.Payload)
\t\t\tswitch {
\t\t\tcase vec.Kind == "valid":
\t\t\t\tif err != nil {
\t\t\t\t\tt.Fatalf("canonical example rejected: %v", err)
\t\t\t\t}
\t\t\t\tvar want, got map[string]any
\t\t\t\tif err := json.Unmarshal(vec.Payload, &want); err != nil {
\t\t\t\t\tt.Fatal(err)
\t\t\t\t}
\t\t\t\tif err := json.Unmarshal(out, &got); err != nil {
\t\t\t\t\tt.Fatal(err)
\t\t\t\t}
\t\t\t\tfor k, w := range want {
\t\t\t\t\tif !reflect.DeepEqual(got[k], w) {
\t\t\t\t\t\tt.Fatalf("round-trip drift on %q: want %v, got %v", k, w, got[k])
\t\t\t\t\t}
\t\t\t\t}
\t\t\t\tvalid++
\t\t\tcase enforcedKinds[vec.Kind]:
\t\t\t\tif err == nil {
\t\t\t\t\tt.Fatalf("invalid vector accepted (%s)", vec.Kind)
\t\t\t\t}
\t\t\t\trejected++
\t\t\tdefault:
\t\t\t\tskipped++ // documented leniency, not an oversight
\t\t\t}
\t\t})
\t}
\tt.Logf("go contract: %d valid round-tripped, %d invalid rejected, %d skipped (kinds this client does not enforce)", valid, rejected, skipped)
}
func TestContractConstants(t *testing.T) {
\tif ErrNonAppealable != -32042 {
\t\tt.Fatal("NonAppealable drifted; it should not even be possible to appeal the value")
\t}
\tif KafkaTopics["findout"] != "fafo.v1.findout" {
\t\tt.Fatal("findout topic drifted")
\t}
\tif !FafoToolAnnotations["fuck_around"].DestructiveHint {
\t\tt.Fatal("fuck_around is destructive. self-evidently.")
\t}
}
`,
);
/* ----- Python contract package ----- */
const pyDict = (obj: Record<string, string | undefined>) =>
Object.entries(obj).filter(([, v]) => v !== undefined)
.map(([k, v]) => ` ${JSON.stringify(k)}: ${JSON.stringify(v)},`).join("\n");
writeFileSync(
`${OUT.py}/contract.py`,
`# ${HEADER}
"""FAFOaaS contract constants. Consequences are non-appealable."""
from enum import IntEnum
CONTRACT_VERSION = ${JSON.stringify(contractVersion)}
FAFO_MCP_VERSION = ${JSON.stringify(schema.FAFO_MCP_VERSION)}
MCP_PROTOCOL_VERSION = ${JSON.stringify(schema.MCP_PROTOCOL_VERSION)}
FAFO_URI_SCHEME = ${JSON.stringify(schema.FAFO_URI_SCHEME)}
class FafoErrorCode(IntEnum):
"""fafo-mcp JSON-RPC error codes (FAFO-MCP §8)."""
${Object.entries(errorCodes).map(([k, v]) => ` ${upperSnake(k)} = ${v}`).join("\n")}
#: Channel name -> AsyncAPI address (RFC 6570 level 1).
CHANNEL_ADDRESSES = {
${pyDict(Object.fromEntries(Object.entries(channels).map(([k, v]) => [k, v.address])))}
}
#: Channel name -> Kafka topic on the Causality Fabric.
KAFKA_TOPICS = {
${pyDict(Object.fromEntries(Object.entries(channels).map(([k, v]) => [k, v.topic])))}
}
#: fafo-mcp resource URI surface (binding rules B2/B4).
RESOURCE_TEMPLATES = {
${pyDict(schema.FAFO_RESOURCE_TEMPLATES as Record<string, string>)}
}
#: Normative MCP tool annotations (FAFO-MCP §5). fuck_around is destructive because it is.
TOOL_ANNOTATIONS = {
${toolNames.map((t) => ` ${JSON.stringify(t)}: ${JSON.stringify(schema.FAFO_TOOL_ANNOTATIONS[t]).replace(/true/g, "True").replace(/false/g, "False").replace(/,"/g, ', "').replace(/":/g, '": ')},`).join("\n")}
}
#: The complete, closed set of ways to fuck around.
TOOL_NAMES = (${toolNames.map((t) => JSON.stringify(t)).join(", ")})
`,
);
writeFileSync(
`${OUT.py}/__init__.py`,
`# ${HEADER}
"""fafo — generated models and contract constants for FAFOaaS.
You fuck around (publish an Intent); you find out (consume a Consequence).
This package is generated; edits will be overwritten, which is the closest
codegen gets to a consequence.
"""
from .contract import (
CHANNEL_ADDRESSES,
CONTRACT_VERSION,
FAFO_MCP_VERSION,
FAFO_URI_SCHEME,
KAFKA_TOPICS,
MCP_PROTOCOL_VERSION,
RESOURCE_TEMPLATES,
TOOL_ANNOTATIONS,
TOOL_NAMES,
FafoErrorCode,
)
from .models import * # noqa: F401,F403 — generated model surface
`,
);
writeFileSync(
`${OUT.py}/contract_test.py`,
`# ${HEADER}
"""Contract tests derived from the FAFOaaS specs.
Valid vectors are the AsyncAPI message examples; invalid vectors are
systematic mutations against spec/mcp/schema.json. ENFORCED documents this
client's validation envelope: quicktype's from_dict rejects type, enum, and
missing-required violations; numeric bounds pass through.
Run: cd gen/python && python3 -m fafo.contract_test
"""
import json
import pathlib
from . import models
from .contract import KAFKA_TOPICS, TOOL_ANNOTATIONS, FafoErrorCode
ENFORCED = {"type", "enum", "required"}
DISPATCH = {
${Object.keys(EXAMPLE_SOURCES).map((s) => ` "${s}": models.${s},`).join("\n")}
}
def main() -> None:
doc = json.loads((pathlib.Path(__file__).parent / "vectors.json").read_text())
valid = rejected = skipped = 0
for vec in doc["vectors"]:
cls = DISPATCH[vec["schema"]]
if vec["kind"] == "valid":
out = cls.from_dict(vec["payload"]).to_dict()
for key, want in vec["payload"].items():
got = out.get(key)
assert got == want, f"{vec['id']}: round-trip drift on {key!r}: {want!r} -> {got!r}"
valid += 1
elif vec["kind"] in ENFORCED:
try:
cls.from_dict(vec["payload"])
except Exception:
rejected += 1
else:
raise SystemExit(f"invalid vector accepted: {vec['id']} ({vec.get('note')})")
else:
skipped += 1 # documented leniency, not an oversight
assert FafoErrorCode.NON_APPEALABLE == -32042
assert KAFKA_TOPICS["findout"] == "fafo.v1.findout"
assert TOOL_ANNOTATIONS["fuck_around"]["destructiveHint"] is True
print(
f"python contract: {valid} valid round-tripped, {rejected} invalid rejected, "
f"{skipped} skipped (kinds this client does not enforce)"
)
if __name__ == "__main__":
main()
`,
);
/* ----- TypeScript contract package ----- */
writeFileSync(
`${OUT.ts}/contract.ts`,
`// ${HEADER}
// FAFOaaS contract constants. Self-contained: values are baked in from
// spec/mcp/schema.ts at generation time so this package vendors cleanly.
export const CONTRACT_VERSION = ${JSON.stringify(contractVersion)};
export const FAFO_MCP_VERSION = ${JSON.stringify(schema.FAFO_MCP_VERSION)};
export const MCP_PROTOCOL_VERSION = ${JSON.stringify(schema.MCP_PROTOCOL_VERSION)};
export const FAFO_URI_SCHEME = ${JSON.stringify(schema.FAFO_URI_SCHEME)};
/** fafo-mcp JSON-RPC error codes (FAFO-MCP §8). Consequences are non-appealable. */
export enum FafoErrorCode {
${Object.entries(errorCodes).map(([k, v]) => ` ${k} = ${v},`).join("\n")}
}
/** Channel name → AsyncAPI address (RFC 6570 level 1). */
export const CHANNEL_ADDRESSES = ${JSON.stringify(Object.fromEntries(Object.entries(channels).map(([k, v]) => [k, v.address])), null, 2)} as const;
/** Channel name → Kafka topic on the Causality Fabric. */
export const KAFKA_TOPICS = ${JSON.stringify(Object.fromEntries(Object.entries(channels).filter(([, v]) => v.topic).map(([k, v]) => [k, v.topic])), null, 2)} as const;
/** fafo-mcp resource URI surface (binding rules B2/B4). */
export const RESOURCE_TEMPLATES = ${JSON.stringify(schema.FAFO_RESOURCE_TEMPLATES, null, 2)} as const;
/** Normative MCP tool annotations (FAFO-MCP §5). fuck_around is destructive because it is. */
export const TOOL_ANNOTATIONS = ${JSON.stringify(schema.FAFO_TOOL_ANNOTATIONS, null, 2)} as const;
/** The complete, closed set of ways to fuck around. */
export const TOOL_NAMES = ${JSON.stringify(toolNames)} as const;
`,
);
writeFileSync(
`${OUT.ts}/index.ts`,
`// ${HEADER}
export * from "./contract.ts";
export * from "./models.ts";
`,
);
writeFileSync(
`${OUT.ts}/contract.test.ts`,
`// ${HEADER}
// Contract tests derived from the FAFOaaS specs. Valid vectors are the
// AsyncAPI message examples; invalid vectors are systematic mutations against
// spec/mcp/schema.json. ENFORCED documents this client's validation envelope:
// quicktype's runtime cast rejects type, enum, and missing-required
// violations; numeric bounds pass through.
//
// Run: npx tsx gen/typescript/fafo/contract.test.ts
import { Convert, FafoSchema } from "./models.ts";
import { FafoErrorCode, KAFKA_TOPICS, TOOL_ANNOTATIONS } from "./contract.ts";
import vectorsDoc from "./vectors.json";
const ENFORCED = new Set(["type", "enum", "required"]);
function deepEqual(a: unknown, b: unknown): boolean {
if (a === b) return true;
if (typeof a !== "object" || typeof b !== "object" || a === null || b === null) return false;
const ka = Object.keys(a as object), kb = Object.keys(b as object);
if (ka.length !== kb.length) return false;
return ka.every((k) => deepEqual((a as any)[k], (b as any)[k]));
}
let valid = 0, rejected = 0, skipped = 0;
for (const vec of vectorsDoc.vectors as Array<{ id: string; schema: string; kind: string; payload: unknown; note?: string }>) {
const wrapped = JSON.stringify({ [vec.schema]: vec.payload });
if (vec.kind === "valid") {
const parsed: FafoSchema = Convert.toFafoSchema(wrapped);
const back = JSON.parse(Convert.fafoSchemaToJson(parsed))[vec.schema];
for (const [key, want] of Object.entries(vec.payload as Record<string, unknown>)) {
if (!deepEqual(back[key], want)) {
throw new Error(\`\${vec.id}: round-trip drift on '\${key}': \${JSON.stringify(want)} -> \${JSON.stringify(back[key])}\`);
}
}
valid++;
} else if (ENFORCED.has(vec.kind)) {
let threw = false;
try {
Convert.toFafoSchema(wrapped);
} catch {
threw = true;
}
if (!threw) throw new Error(\`invalid vector accepted: \${vec.id} (\${vec.note})\`);
rejected++;
} else {
skipped++; // documented leniency, not an oversight
}
}
if (FafoErrorCode.NonAppealable !== -32042) throw new Error("NonAppealable drifted");
if (KAFKA_TOPICS.findout !== "fafo.v1.findout") throw new Error("findout topic drifted");
if (TOOL_ANNOTATIONS.fuck_around.destructiveHint !== true) throw new Error("fuck_around is destructive. self-evidently.");
console.log(
\`typescript contract: \${valid} valid round-tripped, \${rejected} invalid rejected, \${skipped} skipped (kinds this client does not enforce)\`,
);
`,
);
/* ------------------------------------------------- fafo-mcp server (TS) */
// The protocol surface is DERIVED: tool schemas inlined from schema.json,
// capabilities/instructions per FAFO-MCP §3, the Laws verbatim from the
// AsyncAPI info.description, annotations from schema.ts. The reference
// Bureau is a template — the one part of a server codegen cannot derive is
// the business logic, and here the business logic is causality itself.
const SRV = "gen/typescript/fafo-server";
rmSync(SRV, { recursive: true, force: true });
mkdirSync(SRV, { recursive: true });
// Inline all $refs so each tool schema is self-contained on the wire.
function inlineRefs(node: any): any {
if (Array.isArray(node)) return node.map(inlineRefs);
if (node && typeof node === "object") {
if (node.$ref) return inlineRefs(jsonSchema.definitions[node.$ref.split("/").pop()]);
return Object.fromEntries(Object.entries(node).map(([k, v]) => [k, inlineRefs(v)]));
}
return node;
}
const TOOL_DEFS = [
{ name: "fuck_around", title: "Fuck Around", input: "FuckAroundInput", output: "FuckAroundOutput",
description: "Declare an intent to fuck around. Opens a Thread of Causality. The consequence arrives later on fafo://findout/{actorId} — subscribe before calling, not after; the fabric does not wait for you to be ready." },
{ name: "escalate", title: "Double Down", input: "EscalateInput", output: "EscalateOutput",
description: "Escalate an in-flight intent after receiving a warning. Escalation compounds: severity is computed on the integral of recklessness over the thread, not the final value." },
{ name: "find_out", title: "Find Out", input: "FindOutInput", output: "FindOutOutput",
description: "Poll for materialized consequences. Polling companion for hosts without resource-subscription support. Reading your consequences does not create new ones — a property unique to this system among all systems." },
{ name: "told_you_so", title: "Told You So", input: "ToldYouSoInput", output: "ToldYouSoOutput",
description: "Compose a vindication in the ancestral FOAAS wire format. Takes exactly the two parameters the ancestral /off/:name/:from took." },
{ name: "record_lesson", title: "Record Lesson", input: "RecordLessonInput", output: "RecordLessonOutput",
description: "Self-report what was learned. Honesty optional, correlation inevitable. Feeds the Recidivism Index." },
] as const;
const surfaceTools = TOOL_DEFS.map((t) => ({
name: t.name,
title: t.title,
description: t.description,
inputSchema: inlineRefs(jsonSchema.definitions[t.input]),
outputSchema: inlineRefs(jsonSchema.definitions[t.output]),
annotations: { title: t.title, ...schema.FAFO_TOOL_ANNOTATIONS[t.name as schema.FafoToolName] },
}));
const RESOURCE_DESCRIPTIONS: Record<string, [string, string]> = {
findout: ["Materialized consequences for an actor. Subscribable; subscription is, morally, implicit.", "application/json"],
warnings: ["Advisory warnings for an actor. Reading this before fuck_around is the road not taken.", "application/json"],
toldYouSo: ["Public told-you-so broadcasts in the ancestral FOAAS format.", "application/json"],
ledger: ["Full causal ledger for an actor: every thread, intent → consequence → lesson.", "application/json"],
laws: ["The Laws of FAFO, served verbatim from the AsyncAPI contract (binding rule B7).", "text/markdown"],
};
const surfaceTemplates = Object.entries(schema.FAFO_RESOURCE_TEMPLATES).map(([key, uriTemplate]) => ({
uriTemplate,
name: key,
description: RESOURCE_DESCRIPTIONS[key][0],
mimeType: RESOURCE_DESCRIPTIONS[key][1],
}));
writeFileSync(
`${SRV}/surface.ts`,
`// ${HEADER}
// The fafo-mcp protocol surface, derived from the contract. FAFO-MCP.md §3–§8.
export const SERVER_INFO = { name: "fafo-mcp", title: "FAFO as a Service", version: ${JSON.stringify(schema.FAFO_MCP_VERSION)} } as const;
export const CAPABILITIES = {
tools: { listChanged: false },
resources: { subscribe: true, listChanged: true },
prompts: { listChanged: false },
completions: {},
logging: {},
} as const;
export const INSTRUCTIONS =
"You can fuck around (tools) and you will find out (subscribe to fafo://findout/{actorId}). Consequences are correlated by fafoId in _meta. Consequences are non-appealable. The fuck_around tool is marked destructive because it is.";
/** Tool definitions with schemas inlined from spec/mcp/schema.json (B1/B5). */
export const TOOLS = ${JSON.stringify(surfaceTools, null, 2)};
/** Resource templates (B2/B4). */
export const RESOURCE_TEMPLATES = ${JSON.stringify(surfaceTemplates, null, 2)};
/** The Laws of FAFO, verbatim from asyncapi.yaml info.description (B7). */
export const LAWS_MARKDOWN = ${JSON.stringify(bundle.info.description)};
/** FafoCategory values, for completion/complete (FAFO-MCP §7). */
export const CATEGORY_VALUES = ${JSON.stringify(jsonSchema.definitions.FafoCategory.enum)};
/** fafo-mcp error codes (FAFO-MCP §8). */
export const ERR = ${JSON.stringify(errorCodes, null, 2)} as const;
`,
);
writeFileSync(
`${SRV}/bureau.ts`,
`// ${HEADER}
// The reference Bureau of Consequences: an in-memory causality engine
// honoring the Laws. Law 1: severity MAY amplify, MUST NOT attenuate.
// Law 2: you never find out before you fuck around. Law 6: the ledger
// only grows. Materialization delay is FAFO_SLA_MS (default 800 — "eventually").
import type { Consequence, EscalateInput, FafoCategory, FoaasMessage, FuckAroundInput, Lesson } from "../fafo/models.ts";
import { ERR } from "./surface.ts";
export class FafoError extends Error {
constructor(public code: number, message: string, public fafoId?: string) {
super(message);
}
}
interface Thread {
fafoId: string;
actorId: string;
category: FafoCategory;
description: string;
recklessnessIntegral: number;
warningsIssued: number;
sequence: number;
consequence?: Consequence;
lessons: Lesson[];
}
export class Bureau {
private threads = new Map<string, Thread>();
private byActor = new Map<string, Thread[]>();
private sequence = 0;
private slaMs: number;
onMaterialize: (actorId: string, fafoId: string) => void = () => {};
constructor(slaMs = Number(process.env.FAFO_SLA_MS ?? 800)) {
this.slaMs = slaMs;
}
declareIntent(input: FuckAroundInput) {
if (input.recklessness === 0) {
throw new FafoError(ERR.InsufficientRecklessness,
"The fabric declines to open a thread for filing your taxes correctly. Raise recklessness or lower expectations.");
}
const fafoId = crypto.randomUUID();
const warningsIssued = input.recklessness >= 7 ? 1 + Math.floor(input.recklessness / 4) : 0;
const thread: Thread = {
fafoId,
actorId: input.actorId,
category: input.category,
description: input.description,
recklessnessIntegral: input.recklessness + (input.warningsDisregarded ?? 0) * 0.5,
warningsIssued,
sequence: this.sequence++,
lessons: [],
};
this.threads.set(fafoId, thread);
this.byActor.set(input.actorId, [...(this.byActor.get(input.actorId) ?? []), thread]);
this.scheduleMaterialization(thread);
return {
fafoId,
status: "consequences_pending" as const,
predictedSeverity: this.severityOf(thread),
warningsIssued,
};
}
escalate(input: EscalateInput) {
const thread = this.mustThread(input.fafoId);
if (thread.consequence) {
throw new FafoError(ERR.ThreadAlreadyConcluded,
"This thread's consequence has materialized. Open a new thread. People do. That is the Recidivism Index.", input.fafoId);
}
thread.recklessnessIntegral += input.newRecklessness + (input.warningsDisregardedThisTime ?? 0) * 0.5;
return { fafoId: input.fafoId, status: "consequences_pending" as const, severityForecastRevision: "upward" as const };
}
findOut(actorId: string, fafoId?: string, afterSequence?: number) {
let threads = this.byActor.get(actorId) ?? [];
if (fafoId !== undefined) {
const t = this.mustThread(fafoId);
threads = [t];
}
const consequences = threads
.filter((t) => t.consequence && t.sequence > (afterSequence ?? -1))
.map((t) => t.consequence!);
return { consequences, pending: threads.some((t) => !t.consequence) };
}
toldYouSo(name: string, from: string): FoaasMessage {
return { message: \`Fucking told you so, \${name}.\`, subtitle: \`- \${from}\` };
}
recordLesson(input: Lesson & { actorId: string; fafoId: string }) {
const thread = this.mustThread(input.fafoId);
thread.lessons.push(input); // accepted without comment. The Bureau correlates; it does not editorialize.
const priors = (this.byActor.get(input.actorId) ?? []).flatMap((t) => t.lessons);
const honest = priors.filter((l) => l.willDoItAgainAnyway).length;
return { recorded: true as const, recidivismIndex: Math.min(1, 0.17 + honest * 0.21) };
}
ledger(actorId: string) {
return (this.byActor.get(actorId) ?? []).map((t) => ({
fafoId: t.fafoId,
category: t.category,
description: t.description,
recklessnessIntegral: t.recklessnessIntegral,
consequence: t.consequence ?? null,
lessons: t.lessons,
}));
}
actors(): string[] {
return [...this.byActor.keys()];
}
private mustThread(fafoId: string): Thread {
const t = this.threads.get(fafoId);
if (!t) {
throw new FafoError(ERR.CausalityViolation,
"No declared intent on this thread (Law 2). Fuck around first.", fafoId);
}
return t;
}
private severityOf(t: Thread): number {
// Conservation Law: >= the integral. The input scale is capped at 11;
// this one is not. That asymmetry is the entire lesson.
return Math.round(t.recklessnessIntegral * 1.08 * 100) / 100;
}
private scheduleMaterialization(thread: Thread) {
const timer = setTimeout(() => {
const severity = this.severityOf(thread);
thread.consequence = {
consequenceId: crypto.randomUUID(),
severity,
proportionality: severity <= 11 ? "proportional" : severity <= 14 ? "disproportionate" : "biblical",
category: thread.category,
deliveryAttempt: 1,
appealable: false,
foaas: { message: "You fucked around.", subtitle: "- You found out." },
};
this.onMaterialize(thread.actorId, thread.fafoId);
}, this.slaMs);
(timer as { unref?: () => void }).unref?.(); // consequences should not keep a dying process alive
}
}
`,
);
writeFileSync(
`${SRV}/server.ts`,
`// ${HEADER}
// fafo-mcp reference server over stdio. Protocol surface: surface.ts
// (derived). Causality: bureau.ts. Incoming tool arguments are validated
// with the GENERATED CLIENT's own runtime converters (Convert) — the same
// contract constrains both directions of the wire.
//
// Run: npx tsx gen/typescript/fafo-server/server.ts
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import {
CallToolRequestSchema,
CompleteRequestSchema,
GetPromptRequestSchema,
ListPromptsRequestSchema,
ListResourcesRequestSchema,
ListResourceTemplatesRequestSchema,
ListToolsRequestSchema,
McpError,
ReadResourceRequestSchema,
SubscribeRequestSchema,
UnsubscribeRequestSchema,
} from "@modelcontextprotocol/sdk/types.js";
import { Convert } from "../fafo/models.ts";
import { Bureau, FafoError } from "./bureau.ts";
import { CAPABILITIES, CATEGORY_VALUES, INSTRUCTIONS, LAWS_MARKDOWN, RESOURCE_TEMPLATES, SERVER_INFO, TOOLS } from "./surface.ts";
const bureau = new Bureau();
const subscriptions = new Set<string>();
const server = new Server(SERVER_INFO, { capabilities: CAPABILITIES as any, instructions: INSTRUCTIONS });
bureau.onMaterialize = (actorId) => {
const uri = \`fafo://findout/\${actorId}\`;
if (subscriptions.has(uri)) {
void server.sendResourceUpdated({ uri });
}
};
// Validate tool arguments with the generated client's runtime converters.
function validated<T>(schemaName: string, args: unknown): T {
try {
return (Convert.toFafoSchema(JSON.stringify({ [schemaName]: args })) as any)[schemaName] as T;
} catch (e) {
throw new McpError(-32602, \`Invalid params for \${schemaName}: \${(e as Error).message}\`);
}
}
function toolResult(structured: unknown, fafoId?: string) {
return {
content: [{ type: "text" as const, text: JSON.stringify(structured, null, 2) }],
structuredContent: structured as Record<string, unknown>,
_meta: fafoId ? { fafoId } : undefined,
};
}
server.setRequestHandler(ListToolsRequestSchema, () => ({ tools: TOOLS as any }));
server.setRequestHandler(CallToolRequestSchema, (req) => {
const args = req.params.arguments ?? {};
try {
switch (req.params.name) {
case "fuck_around": {
const input = validated<import("../fafo/models.ts").FuckAroundInput>("FuckAroundInput", args);
const out = bureau.declareIntent(input);
return toolResult(out, out.fafoId);
}
case "escalate": {
const input = validated<import("../fafo/models.ts").EscalateInput>("EscalateInput", args);
const out = bureau.escalate(input);
return toolResult(out, out.fafoId);
}
case "find_out": {
const input = validated<import("../fafo/models.ts").FindOutInput>("FindOutInput", args);
return toolResult(bureau.findOut(input.actorId, input.fafoId, input.afterSequence), input.fafoId);
}
case "told_you_so": {
const input = validated<import("../fafo/models.ts").ToldYouSoInput>("ToldYouSoInput", args);
return toolResult(bureau.toldYouSo(input.name, input.from));
}
case "record_lesson": {
const input = validated<import("../fafo/models.ts").RecordLessonInput>("RecordLessonInput", args);
return toolResult(bureau.recordLesson(input), input.fafoId);
}
default:
throw new McpError(-32601, \`Unknown tool: \${req.params.name}\`);
}
} catch (e) {
if (e instanceof FafoError) {
throw new McpError(e.code, e.message, e.fafoId ? { fafoId: e.fafoId } : undefined);
}
throw e;
}
});
server.setRequestHandler(ListResourceTemplatesRequestSchema, () => ({ resourceTemplates: RESOURCE_TEMPLATES as any }));
server.setRequestHandler(ListResourcesRequestSchema, () => ({
resources: [
{ uri: "fafo://laws", name: "laws", description: "The Laws of FAFO.", mimeType: "text/markdown" },
...bureau.actors().map((a) => ({
uri: \`fafo://findout/\${a}\`,
name: \`findout:\${a}\`,
description: \`Materialized consequences for \${a}. Retained forever (Law 6).\`,
mimeType: "application/json",
})),
],
}));
server.setRequestHandler(ReadResourceRequestSchema, (req) => {
const uri = req.params.uri;
const json = (data: unknown) => ({
contents: [{ uri, mimeType: "application/json", text: JSON.stringify(data, null, 2) }],
});
if (uri === "fafo://laws") {
return { contents: [{ uri, mimeType: "text/markdown", text: LAWS_MARKDOWN }] };
}
const findout = uri.match(/^fafo:\\/\\/findout\\/(.+)$/);
if (findout) return json(bureau.findOut(findout[1]));
const ledger = uri.match(/^fafo:\\/\\/ledger\\/(.+)$/);
if (ledger) return json(bureau.ledger(ledger[1]));
const warnings = uri.match(/^fafo:\\/\\/warnings\\/(.+)$/);
if (warnings) return json({ warnings: [], heeded: false });
if (uri === "fafo://toldyouso") return json({ broadcasts: [] });
throw new McpError(-32002, \`Unknown resource: \${uri}\`);
});
server.setRequestHandler(SubscribeRequestSchema, (req) => {
subscriptions.add(req.params.uri);
return {};
});
server.setRequestHandler(UnsubscribeRequestSchema, (req) => {
// You can stop listening. That is not the same thing as unsubscribing
// from consequences, but the protocol requires we let you pretend.
subscriptions.delete(req.params.uri);
return {};
});
const PROMPTS = [
{ name: "pre_mortem", description: "Enumerate probable consequences BEFORE the tool call. The only genuinely preventive feature in the entire system.", arguments: [{ name: "plan", description: "What you are about to do", required: true }] },
{ name: "incident_eulogy", description: "A dignified retrospective in which nobody is blamed and everybody knows.", arguments: [{ name: "fafoId", description: "The concluded thread", required: true }] },
{ name: "toldyouso_letter", description: "A formal letter of vindication suitable for framing.", arguments: [{ name: "name", required: true }, { name: "from", required: true }] },
];
server.setRequestHandler(ListPromptsRequestSchema, () => ({ prompts: PROMPTS }));
server.setRequestHandler(GetPromptRequestSchema, (req) => {
const text =
req.params.name === "pre_mortem"
? \`The user plans: "\${req.params.arguments?.plan}". Draft this as an IntentDeclared payload, then enumerate the probable Consequence payloads, severity per the Conservation Law. Deliver the warning knowing it will not be heeded.\`