@vurb/core 3.6.0 → 3.6.1

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/README.md CHANGED
@@ -1,726 +1,726 @@
1
- <div align="center">
2
-
3
- <picture>
4
- <source media="(prefers-color-scheme: dark)" srcset="https://github.com/user-attachments/assets/86ae1b28-a938-4e12-af29-bfc60a55dbe8" >
5
- <img src="https://github.com/user-attachments/assets/86ae1b28-a938-4e12-af29-bfc60a55dbe8" style="border-radius:8px;background:#000000;padding:10px;border:1px solid #414141;" alt="Vurb.ts">
6
- </picture>
7
-
8
- **The TypeScript Framework for MCP Servers.**<br>
9
- Type-safe tools, structured AI perception, and built-in security. Deploy once — every AI assistant connects instantly.
10
-
11
- [![npm version](https://img.shields.io/npm/v/@vurb/core.svg?color=0ea5e9)](https://www.npmjs.com/package/@vurb/core)
12
- [![Downloads](https://img.shields.io/npm/dw/@vurb/core)](https://www.npmjs.com/package/@vurb/core)
13
- [![TypeScript](https://img.shields.io/badge/TypeScript-5.7+-blue?logo=typescript&logoColor=white)](https://www.typescriptlang.org/)
14
- [![MCP Standard](https://img.shields.io/badge/MCP-Standard-purple)](https://modelcontextprotocol.io/)
15
- [![License](https://img.shields.io/badge/License-Apache_2.0-green)](https://github.com/vinkius-labs/vurb.ts/blob/main/LICENSE)
16
-
17
- [Documentation](https://vurb.vinkius.com/) · [Quick Start](https://vurb.vinkius.com/quickstart-lightspeed) · [API Reference](https://vurb.vinkius.com/api/)
18
-
19
- </div>
20
-
21
- ---
22
-
23
- ## Zero Learning Curve — Ship a SKILL.md, Not a Tutorial
24
-
25
- Every framework you've adopted followed the same loop: read the docs, study the conventions, hit an edge case, search GitHub issues, re-read the docs. Weeks before your first production PR. Your AI coding agent does the same — it hallucinates Express patterns into your Hono project because it has no formal contract to work from.
26
-
27
- Vurb.ts ships a **[SKILL.md](https://agentskills.io)** — a machine-readable architectural contract that your AI agent ingests before generating a single line. Not a tutorial. Not a "getting started guide" the LLM will paraphrase loosely. A **typed specification**: every Fluent API method, every builder chain, every Presenter composition rule, every middleware signature, every file-based routing convention. The agent doesn't approximate — it compiles against the spec.
28
-
29
- **One prompt. Working server. Zero iterations:**
30
-
31
- ```
32
- → "Build an MCP server for patient records with Prisma.
33
- Redact SSN and diagnosis from LLM output. Add an FSM
34
- that gates discharge tools until attending physician signs off."
35
- ```
36
-
37
- The agent reads `SKILL.md` and produces:
38
-
39
- ```typescript
40
- // src/tools/patients/discharge.ts — generated by your AI agent
41
- const PatientPresenter = createPresenter('Patient')
42
- .schema({ id: t.string, name: t.string, ssn: t.string, diagnosis: t.string })
43
- .redactPII(['ssn', 'diagnosis'])
44
- .rules(['HIPAA: diagnosis visible in UI blocks but REDACTED in LLM output']);
45
-
46
- const gate = f.fsm({
47
- id: 'discharge', initial: 'admitted',
48
- states: {
49
- admitted: { on: { SIGN_OFF: 'cleared' } },
50
- cleared: { on: { DISCHARGE: 'discharged' } },
51
- discharged: { type: 'final' },
52
- },
53
- });
54
-
55
- export default f.mutation('patients.discharge')
56
- .describe('Discharge a patient')
57
- .bindState('cleared', 'DISCHARGE')
58
- .returns(PatientPresenter)
59
- .handle(async (input, ctx) => ctx.db.patients.update({
60
- where: { id: input.id }, data: { status: 'discharged' },
61
- }));
62
- ```
63
-
64
- Correct Presenter with `.redactPII()`. FSM gating that makes `patients.discharge` invisible until sign-off. File-based routing. Typed handler. **First pass — no corrections.**
65
-
66
- This works on Cursor, Claude Code, GitHub Copilot, Windsurf, Cline — any agent that can read a file. The `SKILL.md` is the single source of truth: the agent doesn't need to have been trained on Vurb.ts, it just needs to read the spec.
67
-
68
- > **You don't learn Vurb.ts. You don't teach your agent Vurb.ts.** You hand it a 400-line contract. It writes the server. You review the PR.
69
-
70
- ---
71
-
72
- ## Get Started in 5 Seconds
73
-
74
- ```bash
75
- vurb create my-server
76
- cd my-server && vurb dev
77
- ```
78
-
79
- That's it. A production-ready MCP server with file-based routing, Presenters, middleware, tests, and pre-configured connections for **Cursor**, **Claude Desktop**, **Claude Code**, **Windsurf**, **Cline**, and **VS Code + GitHub Copilot**.
80
-
81
- ```
82
- Project name? › my-server
83
- Transport? › stdio
84
- Vector? › vanilla
85
-
86
- ● Scaffolding project — 14 files (6ms)
87
- ● Installing dependencies...
88
- ✔ Done — vurb dev to start
89
- ```
90
-
91
- Choose a vector to scaffold exactly the project you need:
92
-
93
- | Vector | What it scaffolds |
94
- |---|---|
95
- | `vanilla` | `autoDiscover()` file-based routing. Zero external deps |
96
- | `prisma` | Prisma schema + CRUD tools with field-level security |
97
- | `n8n` | n8n workflow bridge — auto-discover webhooks as tools |
98
- | `openapi` | OpenAPI 3.x / Swagger 2.0 → full MVA tool generation |
99
- | `oauth` | RFC 8628 Device Flow authentication |
100
-
101
- ```bash
102
- # Database-driven server with Presenter egress firewall
103
- vurb create my-api --vector prisma --transport sse --yes
104
-
105
- # Bridge your n8n workflows to any MCP client
106
- vurb create ops-bridge --vector n8n --yes
107
-
108
- # REST API → MCP in one command
109
- vurb create petstore --vector openapi --yes
110
- ```
111
-
112
- Drop a file in `src/tools/`, restart — it's a live MCP tool. No central import file, no merge conflicts:
113
-
114
- ```
115
- src/tools/
116
- ├── billing/
117
- │ ├── get_invoice.ts → billing.get_invoice
118
- │ └── pay.ts → billing.pay
119
- ├── users/
120
- │ ├── list.ts → users.list
121
- │ └── ban.ts → users.ban
122
- └── system/
123
- └── health.ts → system.health
124
- ```
125
-
126
- ---
127
-
128
- ## Why Vurb.ts Exists
129
-
130
- Every raw MCP server does the same thing: `JSON.stringify()` the database result and ship it to the LLM. Three catastrophic consequences:
131
-
132
- ```typescript
133
- // What every MCP tutorial teaches
134
- server.setRequestHandler(CallToolRequestSchema, async (request) => {
135
- const { name, arguments: args } = request.params;
136
- if (name === 'get_invoice') {
137
- const invoice = await db.invoices.findUnique(args.id);
138
- return { content: [{ type: 'text', text: JSON.stringify(invoice) }] };
139
- // AI receives: { password_hash, internal_margin, customer_ssn, ... }
140
- }
141
- // ...50 more if/else branches
142
- });
143
- ```
144
-
145
- **Data exfiltration.** `JSON.stringify(invoice)` sends `password_hash`, `internal_margin`, `customer_ssn` — every column — straight to the LLM provider. One field = one GDPR violation.
146
-
147
- **Token explosion.** Every tool schema is sent on every turn, even when irrelevant. System prompt rules for every domain entity are sent globally, bloating context with wasted tokens.
148
-
149
- **Context DDoS.** An unbounded `findMany()` can dump thousands of rows into the context window. The LLM hallucinates. Your API bill explodes.
150
-
151
- ---
152
-
153
- ## The MVA Solution
154
-
155
- Vurb.ts replaces `JSON.stringify()` with a **Presenter** — a deterministic perception layer that controls exactly what the agent sees, knows, and can do next.
156
-
157
- ```
158
- Handler (Model) Presenter (View) Agent (LLM)
159
- ─────────────── ──────────────── ───────────
160
- Raw DB data → Zod-validated schema → Structured
161
- { amount_cents, + System rules perception
162
- password_hash, + UI blocks (charts) package
163
- internal_margin, + Suggested next actions
164
- ssn, ... } + PII redaction
165
- + Cognitive guardrails
166
- - password_hash ← STRIPPED
167
- - internal_margin ← STRIPPED
168
- - ssn ← REDACTED
169
- ```
170
-
171
- The result is not JSON — it's a **Perception Package**:
172
-
173
- ```
174
- Block 1 — DATA: {"id":"INV-001","amount_cents":45000,"status":"pending"}
175
- Block 2 — UI: [ECharts gauge chart config]
176
- Block 3 — RULES: "amount_cents is in CENTS. Divide by 100 for display."
177
- Block 4 — ACTIONS: → billing.pay: "Invoice is pending — process payment"
178
- Block 5 — EMBEDS: [Client Presenter + LineItem Presenter composed]
179
- ```
180
-
181
- No guessing. Undeclared fields rejected. Domain rules travel with data — not in the system prompt. Next actions computed from data state.
182
-
183
- ---
184
-
185
- ## Before vs. After
186
-
187
- **Before** — raw MCP:
188
-
189
- ```typescript
190
- case 'get_invoice':
191
- const invoice = await db.invoices.findUnique(args.id);
192
- return { content: [{ type: 'text', text: JSON.stringify(invoice) }] };
193
- // Leaks internal columns. No rules. No guidance.
194
- ```
195
-
196
- **After** — Vurb.ts with MVA:
197
-
198
- ```typescript
199
- import { createPresenter, suggest, ui, t } from '@vurb/core';
200
-
201
- const InvoicePresenter = createPresenter('Invoice')
202
- .schema({
203
- id: t.string,
204
- amount_cents: t.number.describe('Amount in cents — divide by 100'),
205
- status: t.enum('paid', 'pending', 'overdue'),
206
- })
207
- .rules(['CRITICAL: amount_cents is in CENTS. Divide by 100 for display.'])
208
- .redactPII(['*.customer_ssn', '*.credit_card'])
209
- .ui((inv) => [
210
- ui.echarts({
211
- series: [{ type: 'gauge', data: [{ value: inv.amount_cents / 100 }] }],
212
- }),
213
- ])
214
- .suggest((inv) =>
215
- inv.status === 'pending'
216
- ? [suggest('billing.pay', 'Invoice pending — process payment')]
217
- : [suggest('billing.archive', 'Invoice settled — archive it')]
218
- )
219
- .embed('client', ClientPresenter)
220
- .embed('line_items', LineItemPresenter)
221
- .limit(50);
222
-
223
- export default f.query('billing.get_invoice')
224
- .describe('Get an invoice by ID')
225
- .withString('id', 'Invoice ID')
226
- .returns(InvoicePresenter)
227
- .handle(async (input, ctx) => ctx.db.invoices.findUnique({
228
- where: { id: input.id },
229
- include: { client: true, line_items: true },
230
- }));
231
- ```
232
-
233
- The handler returns raw data. The Presenter shapes absolutely everything the agent perceives.
234
-
235
- ---
236
-
237
- ## Architecture
238
-
239
- ### Egress Firewall — Schema as Security Boundary
240
-
241
- The Presenter's Zod schema acts as a whitelist. **Only declared fields pass through.** A database migration that adds `customer_ssn` doesn't change what the agent sees — the new column is invisible unless you explicitly declare it in the schema.
242
-
243
- ```typescript
244
- const UserPresenter = createPresenter('User')
245
- .schema({ id: t.string, name: t.string, email: t.string });
246
- // password_hash, tenant_id, internal_flags → STRIPPED at RAM level
247
- // A developer CANNOT accidentally expose a new column
248
- ```
249
-
250
- ### DLP Compliance Engine — PII Redaction
251
-
252
- GDPR / LGPD / HIPAA compliance built into the framework. `.redactPII()` compiles a V8-optimized redaction function via `fast-redact` that masks sensitive fields **after** UI blocks and rules have been computed (Late Guillotine Pattern) — the LLM receives `[REDACTED]` instead of real values.
253
-
254
- ```typescript
255
- const PatientPresenter = createPresenter('Patient')
256
- .schema({ name: t.string, ssn: t.string, diagnosis: t.string })
257
- .redactPII(['ssn', 'diagnosis'])
258
- .ui((patient) => [
259
- ui.markdown(`**Patient:** ${patient.name}`),
260
- // patient.ssn available for UI logic — but LLM sees [REDACTED]
261
- ]);
262
- ```
263
-
264
- Custom censors, wildcard paths (`'*.email'`, `'patients[*].diagnosis'`), and centralized PII field lists. **Zero-leak guarantee** — the developer cannot accidentally bypass redaction.
265
-
266
- ### 8 Anti-Hallucination Mechanisms
267
-
268
- ```
269
- ① Action Consolidation → groups operations behind fewer tools → ↓ tokens
270
- ② TOON Encoding → pipe-delimited compact descriptions → ↓ tokens
271
- ③ Zod .strict() → rejects hallucinated params at build → ↓ retries
272
- ④ Self-Healing Errors → directed correction prompts → ↓ retries
273
- ⑤ Cognitive Guardrails → .limit() truncates before LLM sees it → ↓ tokens
274
- ⑥ Agentic Affordances → HATEOAS next-action hints from data → ↓ retries
275
- ⑦ JIT Context Rules → rules travel with data, not globally → ↓ tokens
276
- ⑧ State Sync → RFC 7234 cache-control for agents → ↓ requests
277
- ```
278
-
279
- Each mechanism compounds. Fewer tokens in context, fewer requests per task, less hallucination, lower cost.
280
-
281
- ### FSM State Gate — Temporal Anti-Hallucination
282
-
283
- **The first framework where it is physically impossible for an AI to execute tools out of order.**
284
-
285
- LLMs are chaotic — even with HATEOAS suggestions, a model can ignore them and call `cart.pay` with an empty cart. The FSM State Gate makes temporal hallucination structurally impossible: if the workflow state is `empty`, the `cart.pay` tool **doesn't exist** in `tools/list`. The LLM literally cannot call it.
286
-
287
- ```typescript
288
- const gate = f.fsm({
289
- id: 'checkout',
290
- initial: 'empty',
291
- states: {
292
- empty: { on: { ADD_ITEM: 'has_items' } },
293
- has_items: { on: { CHECKOUT: 'payment', CLEAR: 'empty' } },
294
- payment: { on: { PAY: 'confirmed', CANCEL: 'has_items' } },
295
- confirmed: { type: 'final' },
296
- },
297
- });
298
-
299
- const pay = f.mutation('cart.pay')
300
- .describe('Process payment')
301
- .bindState('payment', 'PAY') // Visible ONLY in 'payment' state
302
- .handle(async (input, ctx) => ctx.db.payments.process(input.method));
303
- ```
304
-
305
- | State | Visible Tools |
306
- |---|---|
307
- | `empty` | `cart.add_item`, `cart.view` |
308
- | `has_items` | `cart.add_item`, `cart.checkout`, `cart.view` |
309
- | `payment` | `cart.pay`, `cart.view` |
310
- | `confirmed` | `cart.view` |
311
-
312
- Three complementary layers: **Format** (Zod validates shape), **Guidance** (HATEOAS suggests the next tool), **Gate** (FSM physically removes wrong tools). XState v5 powered, serverless-ready with `fsmStore`.
313
-
314
- ### Zero-Trust Sandbox — Computation Delegation
315
-
316
- The LLM sends JavaScript logic to your data instead of shipping data to the LLM. Code runs inside a sealed V8 isolate — **zero access** to `process`, `require`, `fs`, `net`, `fetch`, `Buffer`. Timeout kill, memory cap, output limit, automatic isolate recovery, and AbortSignal kill-switch (Connection Watchdog).
317
-
318
- ```typescript
319
- export default f.query('analytics.compute')
320
- .describe('Run a computation on server-side data')
321
- .sandboxed({ timeout: 3000, memoryLimit: 64 })
322
- .handle(async (input, ctx) => {
323
- const data = await ctx.db.records.findMany();
324
- const engine = f.sandbox({ timeout: 3000, memoryLimit: 64 });
325
- try {
326
- const result = await engine.execute(input.expression, data);
327
- if (!result.ok) return f.error('VALIDATION_ERROR', result.error)
328
- .suggest('Fix the JavaScript expression and retry.');
329
- return result.value;
330
- } finally { engine.dispose(); }
331
- });
332
- ```
333
-
334
- `.sandboxed()` auto-injects HATEOAS instructions into the tool description — the LLM knows exactly how to format its code. Prototype pollution contained. `constructor.constructor` escape blocked. One isolate per engine, new pristine context per call.
335
-
336
- ### State Sync — Temporal Awareness for Agents
337
-
338
- LLMs have no sense of time. After `sprints.list` then `sprints.create`, the agent still believes the list is unchanged. Vurb.ts injects RFC 7234-inspired cache-control signals:
339
-
340
- ```typescript
341
- const listSprints = f.query('sprints.list')
342
- .stale() // no-store — always re-fetch
343
- .handle(async (input, ctx) => ctx.db.sprints.findMany());
344
-
345
- const createSprint = f.action('sprints.create')
346
- .invalidates('sprints.*', 'tasks.*') // causal cross-domain invalidation
347
- .withString('name', 'Sprint name')
348
- .handle(async (input, ctx) => ctx.db.sprints.create(input));
349
- // After mutation: [System: Cache invalidated for sprints.*, tasks.* — caused by sprints.create]
350
- // Failed mutations emit nothing — state didn't change.
351
- ```
352
-
353
- Registry-level policies with `f.stateSync()`, glob patterns (`*`, `**`), policy overlap detection, observability hooks, and MCP `notifications/resources/updated` emission.
354
-
355
- ### Prompt Engine — Server-Side Templates
356
-
357
- MCP Prompts as executable server-side templates with the same Fluent API as tools. Middleware, hydration timeout, schema-informed coercion, interceptors, multi-modal messages, and the Presenter bridge:
358
-
359
- ```typescript
360
- const IncidentAnalysis = f.prompt('incident_analysis')
361
- .title('Incident Analysis')
362
- .describe('Structured analysis of a production incident')
363
- .tags('engineering', 'ops')
364
- .input({
365
- incident_id: { type: 'string', description: 'Incident ticket ID' },
366
- severity: { enum: ['sev1', 'sev2', 'sev3'] as const },
367
- })
368
- .use(requireAuth, requireRole('engineer'))
369
- .timeout(10_000)
370
- .handler(async (ctx, { incident_id, severity }) => {
371
- const incident = await ctx.db.incidents.findUnique({ where: { id: incident_id } });
372
- return {
373
- messages: [
374
- PromptMessage.system(`You are a Senior SRE. Severity: ${severity.toUpperCase()}.`),
375
- ...PromptMessage.fromView(IncidentPresenter.make(incident, ctx)),
376
- PromptMessage.user('Begin root cause analysis.'),
377
- ],
378
- };
379
- });
380
- ```
381
-
382
- `PromptMessage.fromView()` decomposes any Presenter into prompt messages — same schema, same rules, same affordances in both tools and prompts. Multi-modal with `.image()`, `.audio()`, `.resource()`. Interceptors inject compliance footers after every handler. `PromptRegistry` with filtering, pagination, and lifecycle sync.
383
-
384
- ### Agent Skills — Progressive Instruction Distribution
385
-
386
- **No other MCP framework has this.** Distribute domain expertise to AI agents on demand via MCP. Three-layer progressive disclosure — the agent searches a lightweight index, loads only the relevant SKILL.md, and reads auxiliary files on demand. Zero context window waste.
387
-
388
- ```typescript
389
- import { SkillRegistry, autoDiscoverSkills, createSkillTools } from '@vurb/skills';
390
-
391
- const skills = new SkillRegistry();
392
- await autoDiscoverSkills(skills, './skills');
393
- const [search, load, readFile] = createSkillTools(f, skills);
394
- registry.registerAll(search, load, readFile);
395
- ```
396
-
397
- Skills follow the [agentskills.io](https://agentskills.io) open standard — SKILL.md with YAML frontmatter. `skills.search` returns the lightweight index. `skills.load` returns full instructions. `skills.read_file` gives access to auxiliary files with **path traversal protection** (only files within the skill's directory). Custom search engines supported.
398
-
399
- ```
400
- skills/
401
- ├── deployment/
402
- │ ├── SKILL.md # name, description, full instructions
403
- │ └── scripts/
404
- │ └── deploy.sh # accessible via skills.read_file
405
- └── database-migration/
406
- └── SKILL.md
407
- ```
408
-
409
- ### Fluent API — Semantic Verbs & Chainable Builders
410
-
411
- ```typescript
412
- f.query('users.list') // readOnly: true — no side effects
413
- f.action('users.create') // neutral — creates or updates
414
- f.mutation('users.delete') // destructive: true — triggers confirmation dialogs
415
- ```
416
-
417
- Every builder method is chainable and fully typed. Types accumulate as you chain — the final `.handle()` has 100% accurate autocomplete with zero annotations:
418
-
419
- ```typescript
420
- export const deploy = f.mutation('infra.deploy')
421
- .describe('Deploy infrastructure')
422
- .instructions('Use ONLY after the user explicitly requests deployment.')
423
- .withEnum('env', ['staging', 'production'] as const, 'Target environment')
424
- .concurrency({ max: 2, queueSize: 5 })
425
- .egress(1_000_000)
426
- .idempotent()
427
- .invalidates('infra.*')
428
- .returns(DeployPresenter)
429
- .handle(async function* (input, ctx) {
430
- yield progress(10, 'Cloning repository...');
431
- await cloneRepo(ctx.repoUrl);
432
- yield progress(90, 'Running tests...');
433
- const results = await runTests();
434
- yield progress(100, 'Done!');
435
- return results;
436
- });
437
- ```
438
-
439
- `.instructions()` embeds prompt engineering. `.concurrency()` prevents backend overload. `.egress()` caps response size. `yield progress()` streams MCP progress notifications. `.cached()` / `.stale()` / `.invalidates()` control temporal awareness. `.sandboxed()` enables computation delegation. `.bindState()` enables FSM gating.
440
-
441
- ### Middleware — Pre-Compiled, Zero-Allocation
442
-
443
- tRPC-style context derivation. Middleware chains compiled at registration time into a single nested function — O(1) dispatch, no array iteration, no per-request allocation:
444
-
445
- ```typescript
446
- const requireAuth = f.middleware(async (ctx) => {
447
- const user = await db.getUser(ctx.token);
448
- if (!user) throw new Error('Unauthorized');
449
- return { user, permissions: user.permissions };
450
- });
451
-
452
- // ctx.user and ctx.permissions — fully typed downstream. Zero annotations.
453
- ```
454
-
455
- Stack `.use()` calls for layered derivations: auth → permissions → tenant resolution → audit logging. Same `MiddlewareFn` signature works for both tools and prompts.
456
-
457
- ### Fluent Router — Grouped Tooling
458
-
459
- ```typescript
460
- const users = f.router('users')
461
- .describe('User management')
462
- .use(requireAuth)
463
- .tags('core');
464
-
465
- export const listUsers = users.query('list').describe('List users').handle(/* ... */);
466
- export const banUser = users.mutation('ban').describe('Ban a user').handle(/* ... */);
467
- // Middleware, tags, prefix — all inherited automatically
468
- ```
469
-
470
- Discriminator enum compilation. Per-field annotations tell the LLM which parameters belong to which action. Tool exposition: `flat` (independent MCP tools) or `grouped` (one tool with enum discriminator).
471
-
472
- ### tRPC-Style Client — Compile-Time Route Validation
473
-
474
- ```typescript
475
- import { createVurbClient } from '@vurb/core';
476
- import type { AppRouter } from './server.js';
477
-
478
- const client = createVurbClient<AppRouter>(transport);
479
-
480
- await client.execute('projects.create', { workspace_id: 'ws_1', name: 'V2' });
481
- // TS error on typos ('projetcs.create'), missing fields, type mismatches.
482
- // Zero runtime cost. Client middleware (auth, logging). Batch execution.
483
- ```
484
-
485
- `createTypedRegistry()` is a curried double-generic — first call sets `TContext`, second infers all builder types. `InferRouter` is pure type-level.
486
-
487
- ### Self-Healing Errors
488
-
489
- ```typescript
490
- // Validation errors → directed correction prompts
491
- ❌ Validation failed for 'users.create':
492
- • email — Invalid email format. You sent: 'admin@local'.
493
- Expected: a valid email address (e.g. user@example.com).
494
- 💡 Fix the fields above and call the action again.
495
-
496
- // Business-logic errors → structured recovery with fluent builder
497
- return f.error('NOT_FOUND', `Project '${input.id}' not found`)
498
- .suggest('Call projects.list to find valid IDs')
499
- .actions('projects.list')
500
- .build();
501
- ```
502
-
503
- ### Capability Governance — Cryptographic Surface Integrity
504
-
505
- Nine modules for SOC2-auditable AI deployments:
506
-
507
- ```bash
508
- vurb lock --server ./src/server.ts # Generate vurb.lock
509
- vurb lock --check --server ./src/server.ts # Gate CI builds
510
- ```
511
-
512
- - **Capability Lockfile** — deterministic, git-diffable artifact capturing every tool's behavioral contract
513
- - **Surface Integrity** — SHA-256 behavioral fingerprinting
514
- - **Contract Diffing** — semantic delta engine with severity classification
515
- - **Zero-Trust Attestation** — HMAC-SHA256 signing and runtime verification
516
- - **Blast Radius Analysis** — entitlement scanning (filesystem, network, subprocess) with evasion detection
517
- - **Token Economics** — cognitive overload profiling
518
- - **Semantic Probing** — LLM-as-a-Judge for behavioral drift
519
- - **Self-Healing Context** — contract delta injection into validation errors
520
-
521
- PR diffs show exactly what changed in the AI-facing surface:
522
-
523
- ```diff
524
- "invoices": {
525
- - "integrityDigest": "sha256:f6e5d4c3b2a1...",
526
- + "integrityDigest": "sha256:9a8b7c6d5e4f...",
527
- "behavior": {
528
- - "systemRulesFingerprint": "static:abc",
529
- + "systemRulesFingerprint": "dynamic",
530
- }
531
- }
532
- ```
533
-
534
- ---
535
-
536
- ## Code Generators
537
-
538
- ### OpenAPI → MCP in One Command
539
-
540
- Turn any **REST/OpenAPI 3.x or Swagger 2.0** spec into a working MCP server — code generation or runtime proxy:
541
-
542
- ```bash
543
- npx openapi-gen generate -i ./petstore.yaml -o ./generated
544
- API_BASE_URL=https://api.example.com npx tsx ./generated/server.ts
545
- ```
546
-
547
- Generates `models/` (Zod `.strict()` schemas), `views/` (Presenters), `agents/` (tool definitions with inferred annotations), `server.ts` (bootstrap). HTTP method → MCP annotation inference: `GET` → `readOnly`, `DELETE` → `destructive`, `PUT` → `idempotent`.
548
-
549
- Runtime proxy mode with `loadOpenAPI()` for instant prototyping — no code generation step.
550
-
551
- ### Prisma → MCP with Field-Level Security
552
-
553
- A Prisma Generator that produces Vurb.ts tools and Presenters with field-level security, tenant isolation, and OOM protection:
554
-
555
- ```prisma
556
- generator mcp {
557
- provider = "vurb-prisma-gen"
558
- output = "../src/tools/database"
559
- }
560
-
561
- model User {
562
- id String @id @default(uuid())
563
- email String @unique
564
- passwordHash String /// @vurb.hide ← physically excluded from schema
565
- stripeToken String /// @vurb.hide ← physically excluded from schema
566
- creditScore Int /// @vurb.describe("Score 0-1000. Above 700 is PREMIUM.")
567
- tenantId String /// @vurb.tenantKey ← injected into every WHERE clause
568
- }
569
- ```
570
-
571
- `npx prisma generate` → typed CRUD tools with pagination capped at 50, tenant isolation at the generated code level. Cross-tenant access is structurally impossible.
572
-
573
- ### n8n Workflows → MCP Tools
574
-
575
- Auto-discover n8n webhook workflows as MCP tools with tag filtering, live polling, and MVA interception:
576
-
577
- ```typescript
578
- const n8n = await createN8nConnector({
579
- url: process.env.N8N_URL!,
580
- apiKey: process.env.N8N_API_KEY!,
581
- includeTags: ['ai-enabled'],
582
- pollInterval: 60_000,
583
- onChange: () => server.notification({ method: 'notifications/tools/list_changed' }),
584
- });
585
- ```
586
-
587
- n8n handles the Stripe/Salesforce/webhook logic. Vurb.ts provides typing, Presenters, middleware, and access control.
588
-
589
- ---
590
-
591
- ## Inspector — Real-Time Dashboard
592
-
593
- ```bash
594
- vurb inspect # Auto-discover and connect
595
- vurb inspect --demo # Built-in simulator
596
- ```
597
-
598
- ```
599
- ┌──────────────────────────────────────────────────────────────┐
600
- │ ● LIVE: PID 12345 │ RAM: [█████░░░] 28MB │ UP: 01:23 │
601
- ├───────────────────────┬──────────────────────────────────────┤
602
- │ TOOL LIST │ X-RAY: billing.create_invoice │
603
- │ ✓ billing.create │ LATE GUILLOTINE: │
604
- │ ✓ billing.get │ DB Raw : 4.2KB │
605
- │ ✗ users.delete │ Wire : 1.1KB │
606
- │ ✓ system.health │ SAVINGS : ████████░░ 73.8% │
607
- ├───────────────────────┴──────────────────────────────────────┤
608
- │ 19:32:01 ROUTE billing.create │ 19:32:01 EXEC ✓ 45ms│
609
- └──────────────────────────────────────────────────────────────┘
610
- ```
611
-
612
- Connects via **Shadow Socket** (Named Pipe / Unix Domain Socket) — no stdio interference, no port conflicts. Real-time tool list, request stream, Late Guillotine visualization.
613
-
614
- ---
615
-
616
- ## Testing — Full Pipeline in RAM
617
-
618
- `@vurb/testing` runs the actual execution pipeline — same code path as production — and returns `MvaTestResult` with each MVA layer decomposed:
619
-
620
- ```typescript
621
- import { createVurbTester } from '@vurb/testing';
622
-
623
- const tester = createVurbTester(registry, {
624
- contextFactory: () => ({ prisma: mockPrisma, tenantId: 't_42', role: 'ADMIN' }),
625
- });
626
-
627
- describe('SOC2 Data Governance', () => {
628
- it('strips PII before it reaches the LLM', async () => {
629
- const result = await tester.callAction('db_user', 'find_many', { take: 10 });
630
- for (const user of result.data) {
631
- expect(user).not.toHaveProperty('passwordHash');
632
- expect(user).not.toHaveProperty('tenantId');
633
- }
634
- });
635
-
636
- it('sends governance rules with data', async () => {
637
- const result = await tester.callAction('db_user', 'find_many', { take: 5 });
638
- expect(result.systemRules).toContain('Email addresses are PII.');
639
- });
640
-
641
- it('blocks guest access', async () => {
642
- const result = await tester.callAction('db_user', 'find_many', { take: 5 }, { role: 'GUEST' });
643
- expect(result.isError).toBe(true);
644
- });
645
- });
646
- ```
647
-
648
- Assert every MVA layer: `result.data` (egress firewall), `result.systemRules` (JIT rules), `result.uiBlocks` (server-rendered charts), `result.data.length` (cognitive guardrail), `rawResponse` (HATEOAS hints). Works with Vitest, Jest, Mocha, or `node:test`.
649
-
650
- ---
651
-
652
- ## Deploy Anywhere
653
-
654
- Every tool is transport-agnostic. Same code on Stdio, SSE, and serverless:
655
-
656
- ### Vercel Functions
657
-
658
- ```typescript
659
- import { vercelAdapter } from '@vurb/vercel';
660
- export const POST = vercelAdapter({ registry, contextFactory });
661
- export const runtime = 'edge'; // global edge distribution
662
- ```
663
-
664
- ### Cloudflare Workers
665
-
666
- ```typescript
667
- import { cloudflareWorkersAdapter } from '@vurb/cloudflare';
668
- export default cloudflareWorkersAdapter({ registry, contextFactory });
669
- // D1 for edge-native SQL, KV for sub-ms reads, waitUntil for telemetry
670
- ```
671
-
672
- ---
673
-
674
- ## Ecosystem
675
-
676
- ### Adapters
677
-
678
- | Package | Target |
679
- |---|---|
680
- | [`@vurb/vercel`](https://vurb.vinkius.com/vercel-adapter) | Vercel Functions (Edge / Node.js) |
681
- | [`@vurb/cloudflare`](https://vurb.vinkius.com/cloudflare-adapter) | Cloudflare Workers — zero polyfills |
682
-
683
- ### Generators & Connectors
684
-
685
- | Package | Purpose |
686
- |---|---|
687
- | [`@vurb/openapi-gen`](https://vurb.vinkius.com/openapi-gen) | Generate typed tools from OpenAPI 3.x / Swagger 2.0 specs |
688
- | [`@vurb/prisma-gen`](https://vurb.vinkius.com/prisma-gen) | Generate CRUD tools with field-level security from Prisma |
689
- | [`@vurb/n8n`](https://vurb.vinkius.com/n8n-connector) | Auto-discover n8n workflows as MCP tools |
690
- | [`@vurb/aws`](https://vurb.vinkius.com/aws-connector) | Auto-discover AWS Lambda & Step Functions |
691
- | [`@vurb/skills`](https://vurb.vinkius.com/skills) | Progressive instruction distribution for agents |
692
-
693
- ### Security & Auth
694
-
695
- | Package | Purpose |
696
- |---|---|
697
- | [`@vurb/oauth`](https://vurb.vinkius.com/oauth) | RFC 8628 Device Flow authentication |
698
- | [`@vurb/jwt`](https://vurb.vinkius.com/jwt) | JWT verification — HS256/RS256/ES256 + JWKS |
699
- | [`@vurb/api-key`](https://vurb.vinkius.com/api-key) | API key validation with timing-safe comparison |
700
-
701
- ### Developer Experience
702
-
703
- | Package | Purpose |
704
- |---|---|
705
- | [`@vurb/testing`](https://vurb.vinkius.com/testing) | In-memory pipeline testing with MVA layer assertions |
706
- | [`@vurb/inspector`](https://vurb.vinkius.com/inspector) | Real-time terminal dashboard via Shadow Socket |
707
-
708
- ---
709
-
710
- ## Documentation
711
-
712
- Full guides, API reference, and cookbook recipes:
713
-
714
- **[Vurb.ts.vinkius.com](https://vurb.vinkius.com/)**
715
-
716
- ## Contributing
717
-
718
- See [CONTRIBUTING.md](https://github.com/vinkius-labs/vurb.ts/blob/main/CONTRIBUTING.md) for development setup and PR guidelines.
719
-
720
- ## Security
721
-
722
- See [SECURITY.md](https://github.com/vinkius-labs/vurb.ts/blob/main/SECURITY.md) for reporting vulnerabilities.
723
-
724
- ## License
725
-
726
- [Apache 2.0](https://github.com/vinkius-labs/vurb.ts/blob/main/LICENSE)
1
+ <div align="center">
2
+
3
+ <picture>
4
+ <source media="(prefers-color-scheme: dark)" srcset="https://github.com/user-attachments/assets/86ae1b28-a938-4e12-af29-bfc60a55dbe8" >
5
+ <img src="https://github.com/user-attachments/assets/86ae1b28-a938-4e12-af29-bfc60a55dbe8" style="border-radius:8px;background:#000000;padding:10px;border:1px solid #414141;" alt="Vurb.ts">
6
+ </picture>
7
+
8
+ **The TypeScript Framework for MCP Servers.**<br>
9
+ Type-safe tools, structured AI perception, and built-in security. Deploy once — every AI assistant connects instantly.
10
+
11
+ [![npm version](https://img.shields.io/npm/v/@vurb/core.svg?color=0ea5e9)](https://www.npmjs.com/package/@vurb/core)
12
+ [![Downloads](https://img.shields.io/npm/dw/@vurb/core)](https://www.npmjs.com/package/@vurb/core)
13
+ [![TypeScript](https://img.shields.io/badge/TypeScript-5.7+-blue?logo=typescript&logoColor=white)](https://www.typescriptlang.org/)
14
+ [![MCP Standard](https://img.shields.io/badge/MCP-Standard-purple)](https://modelcontextprotocol.io/)
15
+ [![License](https://img.shields.io/badge/License-Apache_2.0-green)](https://github.com/vinkius-labs/vurb.ts/blob/main/LICENSE)
16
+
17
+ [Documentation](https://vurb.vinkius.com/) · [Quick Start](https://vurb.vinkius.com/quickstart-lightspeed) · [API Reference](https://vurb.vinkius.com/api/)
18
+
19
+ </div>
20
+
21
+ ---
22
+
23
+ ## Zero Learning Curve — Ship a SKILL.md, Not a Tutorial
24
+
25
+ Every framework you've adopted followed the same loop: read the docs, study the conventions, hit an edge case, search GitHub issues, re-read the docs. Weeks before your first production PR. Your AI coding agent does the same — it hallucinates Express patterns into your Hono project because it has no formal contract to work from.
26
+
27
+ Vurb.ts ships a **[SKILL.md](https://agentskills.io)** — a machine-readable architectural contract that your AI agent ingests before generating a single line. Not a tutorial. Not a "getting started guide" the LLM will paraphrase loosely. A **typed specification**: every Fluent API method, every builder chain, every Presenter composition rule, every middleware signature, every file-based routing convention. The agent doesn't approximate — it compiles against the spec.
28
+
29
+ **One prompt. Working server. Zero iterations:**
30
+
31
+ ```
32
+ → "Build an MCP server for patient records with Prisma.
33
+ Redact SSN and diagnosis from LLM output. Add an FSM
34
+ that gates discharge tools until attending physician signs off."
35
+ ```
36
+
37
+ The agent reads `SKILL.md` and produces:
38
+
39
+ ```typescript
40
+ // src/tools/patients/discharge.ts — generated by your AI agent
41
+ const PatientPresenter = createPresenter('Patient')
42
+ .schema({ id: t.string, name: t.string, ssn: t.string, diagnosis: t.string })
43
+ .redactPII(['ssn', 'diagnosis'])
44
+ .rules(['HIPAA: diagnosis visible in UI blocks but REDACTED in LLM output']);
45
+
46
+ const gate = f.fsm({
47
+ id: 'discharge', initial: 'admitted',
48
+ states: {
49
+ admitted: { on: { SIGN_OFF: 'cleared' } },
50
+ cleared: { on: { DISCHARGE: 'discharged' } },
51
+ discharged: { type: 'final' },
52
+ },
53
+ });
54
+
55
+ export default f.mutation('patients.discharge')
56
+ .describe('Discharge a patient')
57
+ .bindState('cleared', 'DISCHARGE')
58
+ .returns(PatientPresenter)
59
+ .handle(async (input, ctx) => ctx.db.patients.update({
60
+ where: { id: input.id }, data: { status: 'discharged' },
61
+ }));
62
+ ```
63
+
64
+ Correct Presenter with `.redactPII()`. FSM gating that makes `patients.discharge` invisible until sign-off. File-based routing. Typed handler. **First pass — no corrections.**
65
+
66
+ This works on Cursor, Claude Code, GitHub Copilot, Windsurf, Cline — any agent that can read a file. The `SKILL.md` is the single source of truth: the agent doesn't need to have been trained on Vurb.ts, it just needs to read the spec.
67
+
68
+ > **You don't learn Vurb.ts. You don't teach your agent Vurb.ts.** You hand it a 400-line contract. It writes the server. You review the PR.
69
+
70
+ ---
71
+
72
+ ## Get Started in 5 Seconds
73
+
74
+ ```bash
75
+ vurb create my-server
76
+ cd my-server && vurb dev
77
+ ```
78
+
79
+ That's it. A production-ready MCP server with file-based routing, Presenters, middleware, tests, and pre-configured connections for **Cursor**, **Claude Desktop**, **Claude Code**, **Windsurf**, **Cline**, and **VS Code + GitHub Copilot**.
80
+
81
+ ```
82
+ Project name? › my-server
83
+ Transport? › stdio
84
+ Vector? › vanilla
85
+
86
+ ● Scaffolding project — 14 files (6ms)
87
+ ● Installing dependencies...
88
+ ✔ Done — vurb dev to start
89
+ ```
90
+
91
+ Choose a vector to scaffold exactly the project you need:
92
+
93
+ | Vector | What it scaffolds |
94
+ |---|---|
95
+ | `vanilla` | `autoDiscover()` file-based routing. Zero external deps |
96
+ | `prisma` | Prisma schema + CRUD tools with field-level security |
97
+ | `n8n` | n8n workflow bridge — auto-discover webhooks as tools |
98
+ | `openapi` | OpenAPI 3.x / Swagger 2.0 → full MVA tool generation |
99
+ | `oauth` | RFC 8628 Device Flow authentication |
100
+
101
+ ```bash
102
+ # Database-driven server with Presenter egress firewall
103
+ vurb create my-api --vector prisma --transport sse --yes
104
+
105
+ # Bridge your n8n workflows to any MCP client
106
+ vurb create ops-bridge --vector n8n --yes
107
+
108
+ # REST API → MCP in one command
109
+ vurb create petstore --vector openapi --yes
110
+ ```
111
+
112
+ Drop a file in `src/tools/`, restart — it's a live MCP tool. No central import file, no merge conflicts:
113
+
114
+ ```
115
+ src/tools/
116
+ ├── billing/
117
+ │ ├── get_invoice.ts → billing.get_invoice
118
+ │ └── pay.ts → billing.pay
119
+ ├── users/
120
+ │ ├── list.ts → users.list
121
+ │ └── ban.ts → users.ban
122
+ └── system/
123
+ └── health.ts → system.health
124
+ ```
125
+
126
+ ---
127
+
128
+ ## Why Vurb.ts Exists
129
+
130
+ Every raw MCP server does the same thing: `JSON.stringify()` the database result and ship it to the LLM. Three catastrophic consequences:
131
+
132
+ ```typescript
133
+ // What every MCP tutorial teaches
134
+ server.setRequestHandler(CallToolRequestSchema, async (request) => {
135
+ const { name, arguments: args } = request.params;
136
+ if (name === 'get_invoice') {
137
+ const invoice = await db.invoices.findUnique(args.id);
138
+ return { content: [{ type: 'text', text: JSON.stringify(invoice) }] };
139
+ // AI receives: { password_hash, internal_margin, customer_ssn, ... }
140
+ }
141
+ // ...50 more if/else branches
142
+ });
143
+ ```
144
+
145
+ **Data exfiltration.** `JSON.stringify(invoice)` sends `password_hash`, `internal_margin`, `customer_ssn` — every column — straight to the LLM provider. One field = one GDPR violation.
146
+
147
+ **Token explosion.** Every tool schema is sent on every turn, even when irrelevant. System prompt rules for every domain entity are sent globally, bloating context with wasted tokens.
148
+
149
+ **Context DDoS.** An unbounded `findMany()` can dump thousands of rows into the context window. The LLM hallucinates. Your API bill explodes.
150
+
151
+ ---
152
+
153
+ ## The MVA Solution
154
+
155
+ Vurb.ts replaces `JSON.stringify()` with a **Presenter** — a deterministic perception layer that controls exactly what the agent sees, knows, and can do next.
156
+
157
+ ```
158
+ Handler (Model) Presenter (View) Agent (LLM)
159
+ ─────────────── ──────────────── ───────────
160
+ Raw DB data → Zod-validated schema → Structured
161
+ { amount_cents, + System rules perception
162
+ password_hash, + UI blocks (charts) package
163
+ internal_margin, + Suggested next actions
164
+ ssn, ... } + PII redaction
165
+ + Cognitive guardrails
166
+ - password_hash ← STRIPPED
167
+ - internal_margin ← STRIPPED
168
+ - ssn ← REDACTED
169
+ ```
170
+
171
+ The result is not JSON — it's a **Perception Package**:
172
+
173
+ ```
174
+ Block 1 — DATA: {"id":"INV-001","amount_cents":45000,"status":"pending"}
175
+ Block 2 — UI: [ECharts gauge chart config]
176
+ Block 3 — RULES: "amount_cents is in CENTS. Divide by 100 for display."
177
+ Block 4 — ACTIONS: → billing.pay: "Invoice is pending — process payment"
178
+ Block 5 — EMBEDS: [Client Presenter + LineItem Presenter composed]
179
+ ```
180
+
181
+ No guessing. Undeclared fields rejected. Domain rules travel with data — not in the system prompt. Next actions computed from data state.
182
+
183
+ ---
184
+
185
+ ## Before vs. After
186
+
187
+ **Before** — raw MCP:
188
+
189
+ ```typescript
190
+ case 'get_invoice':
191
+ const invoice = await db.invoices.findUnique(args.id);
192
+ return { content: [{ type: 'text', text: JSON.stringify(invoice) }] };
193
+ // Leaks internal columns. No rules. No guidance.
194
+ ```
195
+
196
+ **After** — Vurb.ts with MVA:
197
+
198
+ ```typescript
199
+ import { createPresenter, suggest, ui, t } from '@vurb/core';
200
+
201
+ const InvoicePresenter = createPresenter('Invoice')
202
+ .schema({
203
+ id: t.string,
204
+ amount_cents: t.number.describe('Amount in cents — divide by 100'),
205
+ status: t.enum('paid', 'pending', 'overdue'),
206
+ })
207
+ .rules(['CRITICAL: amount_cents is in CENTS. Divide by 100 for display.'])
208
+ .redactPII(['*.customer_ssn', '*.credit_card'])
209
+ .ui((inv) => [
210
+ ui.echarts({
211
+ series: [{ type: 'gauge', data: [{ value: inv.amount_cents / 100 }] }],
212
+ }),
213
+ ])
214
+ .suggest((inv) =>
215
+ inv.status === 'pending'
216
+ ? [suggest('billing.pay', 'Invoice pending — process payment')]
217
+ : [suggest('billing.archive', 'Invoice settled — archive it')]
218
+ )
219
+ .embed('client', ClientPresenter)
220
+ .embed('line_items', LineItemPresenter)
221
+ .limit(50);
222
+
223
+ export default f.query('billing.get_invoice')
224
+ .describe('Get an invoice by ID')
225
+ .withString('id', 'Invoice ID')
226
+ .returns(InvoicePresenter)
227
+ .handle(async (input, ctx) => ctx.db.invoices.findUnique({
228
+ where: { id: input.id },
229
+ include: { client: true, line_items: true },
230
+ }));
231
+ ```
232
+
233
+ The handler returns raw data. The Presenter shapes absolutely everything the agent perceives.
234
+
235
+ ---
236
+
237
+ ## Architecture
238
+
239
+ ### Egress Firewall — Schema as Security Boundary
240
+
241
+ The Presenter's Zod schema acts as a whitelist. **Only declared fields pass through.** A database migration that adds `customer_ssn` doesn't change what the agent sees — the new column is invisible unless you explicitly declare it in the schema.
242
+
243
+ ```typescript
244
+ const UserPresenter = createPresenter('User')
245
+ .schema({ id: t.string, name: t.string, email: t.string });
246
+ // password_hash, tenant_id, internal_flags → STRIPPED at RAM level
247
+ // A developer CANNOT accidentally expose a new column
248
+ ```
249
+
250
+ ### DLP Compliance Engine — PII Redaction
251
+
252
+ GDPR / LGPD / HIPAA compliance built into the framework. `.redactPII()` compiles a V8-optimized redaction function via `fast-redact` that masks sensitive fields **after** UI blocks and rules have been computed (Late Guillotine Pattern) — the LLM receives `[REDACTED]` instead of real values.
253
+
254
+ ```typescript
255
+ const PatientPresenter = createPresenter('Patient')
256
+ .schema({ name: t.string, ssn: t.string, diagnosis: t.string })
257
+ .redactPII(['ssn', 'diagnosis'])
258
+ .ui((patient) => [
259
+ ui.markdown(`**Patient:** ${patient.name}`),
260
+ // patient.ssn available for UI logic — but LLM sees [REDACTED]
261
+ ]);
262
+ ```
263
+
264
+ Custom censors, wildcard paths (`'*.email'`, `'patients[*].diagnosis'`), and centralized PII field lists. **Zero-leak guarantee** — the developer cannot accidentally bypass redaction.
265
+
266
+ ### 8 Anti-Hallucination Mechanisms
267
+
268
+ ```
269
+ ① Action Consolidation → groups operations behind fewer tools → ↓ tokens
270
+ ② TOON Encoding → pipe-delimited compact descriptions → ↓ tokens
271
+ ③ Zod .strict() → rejects hallucinated params at build → ↓ retries
272
+ ④ Self-Healing Errors → directed correction prompts → ↓ retries
273
+ ⑤ Cognitive Guardrails → .limit() truncates before LLM sees it → ↓ tokens
274
+ ⑥ Agentic Affordances → HATEOAS next-action hints from data → ↓ retries
275
+ ⑦ JIT Context Rules → rules travel with data, not globally → ↓ tokens
276
+ ⑧ State Sync → RFC 7234 cache-control for agents → ↓ requests
277
+ ```
278
+
279
+ Each mechanism compounds. Fewer tokens in context, fewer requests per task, less hallucination, lower cost.
280
+
281
+ ### FSM State Gate — Temporal Anti-Hallucination
282
+
283
+ **The first framework where it is physically impossible for an AI to execute tools out of order.**
284
+
285
+ LLMs are chaotic — even with HATEOAS suggestions, a model can ignore them and call `cart.pay` with an empty cart. The FSM State Gate makes temporal hallucination structurally impossible: if the workflow state is `empty`, the `cart.pay` tool **doesn't exist** in `tools/list`. The LLM literally cannot call it.
286
+
287
+ ```typescript
288
+ const gate = f.fsm({
289
+ id: 'checkout',
290
+ initial: 'empty',
291
+ states: {
292
+ empty: { on: { ADD_ITEM: 'has_items' } },
293
+ has_items: { on: { CHECKOUT: 'payment', CLEAR: 'empty' } },
294
+ payment: { on: { PAY: 'confirmed', CANCEL: 'has_items' } },
295
+ confirmed: { type: 'final' },
296
+ },
297
+ });
298
+
299
+ const pay = f.mutation('cart.pay')
300
+ .describe('Process payment')
301
+ .bindState('payment', 'PAY') // Visible ONLY in 'payment' state
302
+ .handle(async (input, ctx) => ctx.db.payments.process(input.method));
303
+ ```
304
+
305
+ | State | Visible Tools |
306
+ |---|---|
307
+ | `empty` | `cart.add_item`, `cart.view` |
308
+ | `has_items` | `cart.add_item`, `cart.checkout`, `cart.view` |
309
+ | `payment` | `cart.pay`, `cart.view` |
310
+ | `confirmed` | `cart.view` |
311
+
312
+ Three complementary layers: **Format** (Zod validates shape), **Guidance** (HATEOAS suggests the next tool), **Gate** (FSM physically removes wrong tools). XState v5 powered, serverless-ready with `fsmStore`.
313
+
314
+ ### Zero-Trust Sandbox — Computation Delegation
315
+
316
+ The LLM sends JavaScript logic to your data instead of shipping data to the LLM. Code runs inside a sealed V8 isolate — **zero access** to `process`, `require`, `fs`, `net`, `fetch`, `Buffer`. Timeout kill, memory cap, output limit, automatic isolate recovery, and AbortSignal kill-switch (Connection Watchdog).
317
+
318
+ ```typescript
319
+ export default f.query('analytics.compute')
320
+ .describe('Run a computation on server-side data')
321
+ .sandboxed({ timeout: 3000, memoryLimit: 64 })
322
+ .handle(async (input, ctx) => {
323
+ const data = await ctx.db.records.findMany();
324
+ const engine = f.sandbox({ timeout: 3000, memoryLimit: 64 });
325
+ try {
326
+ const result = await engine.execute(input.expression, data);
327
+ if (!result.ok) return f.error('VALIDATION_ERROR', result.error)
328
+ .suggest('Fix the JavaScript expression and retry.');
329
+ return result.value;
330
+ } finally { engine.dispose(); }
331
+ });
332
+ ```
333
+
334
+ `.sandboxed()` auto-injects HATEOAS instructions into the tool description — the LLM knows exactly how to format its code. Prototype pollution contained. `constructor.constructor` escape blocked. One isolate per engine, new pristine context per call.
335
+
336
+ ### State Sync — Temporal Awareness for Agents
337
+
338
+ LLMs have no sense of time. After `sprints.list` then `sprints.create`, the agent still believes the list is unchanged. Vurb.ts injects RFC 7234-inspired cache-control signals:
339
+
340
+ ```typescript
341
+ const listSprints = f.query('sprints.list')
342
+ .stale() // no-store — always re-fetch
343
+ .handle(async (input, ctx) => ctx.db.sprints.findMany());
344
+
345
+ const createSprint = f.action('sprints.create')
346
+ .invalidates('sprints.*', 'tasks.*') // causal cross-domain invalidation
347
+ .withString('name', 'Sprint name')
348
+ .handle(async (input, ctx) => ctx.db.sprints.create(input));
349
+ // After mutation: [System: Cache invalidated for sprints.*, tasks.* — caused by sprints.create]
350
+ // Failed mutations emit nothing — state didn't change.
351
+ ```
352
+
353
+ Registry-level policies with `f.stateSync()`, glob patterns (`*`, `**`), policy overlap detection, observability hooks, and MCP `notifications/resources/updated` emission.
354
+
355
+ ### Prompt Engine — Server-Side Templates
356
+
357
+ MCP Prompts as executable server-side templates with the same Fluent API as tools. Middleware, hydration timeout, schema-informed coercion, interceptors, multi-modal messages, and the Presenter bridge:
358
+
359
+ ```typescript
360
+ const IncidentAnalysis = f.prompt('incident_analysis')
361
+ .title('Incident Analysis')
362
+ .describe('Structured analysis of a production incident')
363
+ .tags('engineering', 'ops')
364
+ .input({
365
+ incident_id: { type: 'string', description: 'Incident ticket ID' },
366
+ severity: { enum: ['sev1', 'sev2', 'sev3'] as const },
367
+ })
368
+ .use(requireAuth, requireRole('engineer'))
369
+ .timeout(10_000)
370
+ .handler(async (ctx, { incident_id, severity }) => {
371
+ const incident = await ctx.db.incidents.findUnique({ where: { id: incident_id } });
372
+ return {
373
+ messages: [
374
+ PromptMessage.system(`You are a Senior SRE. Severity: ${severity.toUpperCase()}.`),
375
+ ...PromptMessage.fromView(IncidentPresenter.make(incident, ctx)),
376
+ PromptMessage.user('Begin root cause analysis.'),
377
+ ],
378
+ };
379
+ });
380
+ ```
381
+
382
+ `PromptMessage.fromView()` decomposes any Presenter into prompt messages — same schema, same rules, same affordances in both tools and prompts. Multi-modal with `.image()`, `.audio()`, `.resource()`. Interceptors inject compliance footers after every handler. `PromptRegistry` with filtering, pagination, and lifecycle sync.
383
+
384
+ ### Agent Skills — Progressive Instruction Distribution
385
+
386
+ **No other MCP framework has this.** Distribute domain expertise to AI agents on demand via MCP. Three-layer progressive disclosure — the agent searches a lightweight index, loads only the relevant SKILL.md, and reads auxiliary files on demand. Zero context window waste.
387
+
388
+ ```typescript
389
+ import { SkillRegistry, autoDiscoverSkills, createSkillTools } from '@vurb/skills';
390
+
391
+ const skills = new SkillRegistry();
392
+ await autoDiscoverSkills(skills, './skills');
393
+ const [search, load, readFile] = createSkillTools(f, skills);
394
+ registry.registerAll(search, load, readFile);
395
+ ```
396
+
397
+ Skills follow the [agentskills.io](https://agentskills.io) open standard — SKILL.md with YAML frontmatter. `skills.search` returns the lightweight index. `skills.load` returns full instructions. `skills.read_file` gives access to auxiliary files with **path traversal protection** (only files within the skill's directory). Custom search engines supported.
398
+
399
+ ```
400
+ skills/
401
+ ├── deployment/
402
+ │ ├── SKILL.md # name, description, full instructions
403
+ │ └── scripts/
404
+ │ └── deploy.sh # accessible via skills.read_file
405
+ └── database-migration/
406
+ └── SKILL.md
407
+ ```
408
+
409
+ ### Fluent API — Semantic Verbs & Chainable Builders
410
+
411
+ ```typescript
412
+ f.query('users.list') // readOnly: true — no side effects
413
+ f.action('users.create') // neutral — creates or updates
414
+ f.mutation('users.delete') // destructive: true — triggers confirmation dialogs
415
+ ```
416
+
417
+ Every builder method is chainable and fully typed. Types accumulate as you chain — the final `.handle()` has 100% accurate autocomplete with zero annotations:
418
+
419
+ ```typescript
420
+ export const deploy = f.mutation('infra.deploy')
421
+ .describe('Deploy infrastructure')
422
+ .instructions('Use ONLY after the user explicitly requests deployment.')
423
+ .withEnum('env', ['staging', 'production'] as const, 'Target environment')
424
+ .concurrency({ max: 2, queueSize: 5 })
425
+ .egress(1_000_000)
426
+ .idempotent()
427
+ .invalidates('infra.*')
428
+ .returns(DeployPresenter)
429
+ .handle(async function* (input, ctx) {
430
+ yield progress(10, 'Cloning repository...');
431
+ await cloneRepo(ctx.repoUrl);
432
+ yield progress(90, 'Running tests...');
433
+ const results = await runTests();
434
+ yield progress(100, 'Done!');
435
+ return results;
436
+ });
437
+ ```
438
+
439
+ `.instructions()` embeds prompt engineering. `.concurrency()` prevents backend overload. `.egress()` caps response size. `yield progress()` streams MCP progress notifications. `.cached()` / `.stale()` / `.invalidates()` control temporal awareness. `.sandboxed()` enables computation delegation. `.bindState()` enables FSM gating.
440
+
441
+ ### Middleware — Pre-Compiled, Zero-Allocation
442
+
443
+ tRPC-style context derivation. Middleware chains compiled at registration time into a single nested function — O(1) dispatch, no array iteration, no per-request allocation:
444
+
445
+ ```typescript
446
+ const requireAuth = f.middleware(async (ctx) => {
447
+ const user = await db.getUser(ctx.token);
448
+ if (!user) throw new Error('Unauthorized');
449
+ return { user, permissions: user.permissions };
450
+ });
451
+
452
+ // ctx.user and ctx.permissions — fully typed downstream. Zero annotations.
453
+ ```
454
+
455
+ Stack `.use()` calls for layered derivations: auth → permissions → tenant resolution → audit logging. Same `MiddlewareFn` signature works for both tools and prompts.
456
+
457
+ ### Fluent Router — Grouped Tooling
458
+
459
+ ```typescript
460
+ const users = f.router('users')
461
+ .describe('User management')
462
+ .use(requireAuth)
463
+ .tags('core');
464
+
465
+ export const listUsers = users.query('list').describe('List users').handle(/* ... */);
466
+ export const banUser = users.mutation('ban').describe('Ban a user').handle(/* ... */);
467
+ // Middleware, tags, prefix — all inherited automatically
468
+ ```
469
+
470
+ Discriminator enum compilation. Per-field annotations tell the LLM which parameters belong to which action. Tool exposition: `flat` (independent MCP tools) or `grouped` (one tool with enum discriminator).
471
+
472
+ ### tRPC-Style Client — Compile-Time Route Validation
473
+
474
+ ```typescript
475
+ import { createVurbClient } from '@vurb/core';
476
+ import type { AppRouter } from './server.js';
477
+
478
+ const client = createVurbClient<AppRouter>(transport);
479
+
480
+ await client.execute('projects.create', { workspace_id: 'ws_1', name: 'V2' });
481
+ // TS error on typos ('projetcs.create'), missing fields, type mismatches.
482
+ // Zero runtime cost. Client middleware (auth, logging). Batch execution.
483
+ ```
484
+
485
+ `createTypedRegistry()` is a curried double-generic — first call sets `TContext`, second infers all builder types. `InferRouter` is pure type-level.
486
+
487
+ ### Self-Healing Errors
488
+
489
+ ```typescript
490
+ // Validation errors → directed correction prompts
491
+ ❌ Validation failed for 'users.create':
492
+ • email — Invalid email format. You sent: 'admin@local'.
493
+ Expected: a valid email address (e.g. user@example.com).
494
+ 💡 Fix the fields above and call the action again.
495
+
496
+ // Business-logic errors → structured recovery with fluent builder
497
+ return f.error('NOT_FOUND', `Project '${input.id}' not found`)
498
+ .suggest('Call projects.list to find valid IDs')
499
+ .actions('projects.list')
500
+ .build();
501
+ ```
502
+
503
+ ### Capability Governance — Cryptographic Surface Integrity
504
+
505
+ Nine modules for SOC2-auditable AI deployments:
506
+
507
+ ```bash
508
+ vurb lock --server ./src/server.ts # Generate vurb.lock
509
+ vurb lock --check --server ./src/server.ts # Gate CI builds
510
+ ```
511
+
512
+ - **Capability Lockfile** — deterministic, git-diffable artifact capturing every tool's behavioral contract
513
+ - **Surface Integrity** — SHA-256 behavioral fingerprinting
514
+ - **Contract Diffing** — semantic delta engine with severity classification
515
+ - **Zero-Trust Attestation** — HMAC-SHA256 signing and runtime verification
516
+ - **Blast Radius Analysis** — entitlement scanning (filesystem, network, subprocess) with evasion detection
517
+ - **Token Economics** — cognitive overload profiling
518
+ - **Semantic Probing** — LLM-as-a-Judge for behavioral drift
519
+ - **Self-Healing Context** — contract delta injection into validation errors
520
+
521
+ PR diffs show exactly what changed in the AI-facing surface:
522
+
523
+ ```diff
524
+ "invoices": {
525
+ - "integrityDigest": "sha256:f6e5d4c3b2a1...",
526
+ + "integrityDigest": "sha256:9a8b7c6d5e4f...",
527
+ "behavior": {
528
+ - "systemRulesFingerprint": "static:abc",
529
+ + "systemRulesFingerprint": "dynamic",
530
+ }
531
+ }
532
+ ```
533
+
534
+ ---
535
+
536
+ ## Code Generators
537
+
538
+ ### OpenAPI → MCP in One Command
539
+
540
+ Turn any **REST/OpenAPI 3.x or Swagger 2.0** spec into a working MCP server — code generation or runtime proxy:
541
+
542
+ ```bash
543
+ npx openapi-gen generate -i ./petstore.yaml -o ./generated
544
+ API_BASE_URL=https://api.example.com npx tsx ./generated/server.ts
545
+ ```
546
+
547
+ Generates `models/` (Zod `.strict()` schemas), `views/` (Presenters), `agents/` (tool definitions with inferred annotations), `server.ts` (bootstrap). HTTP method → MCP annotation inference: `GET` → `readOnly`, `DELETE` → `destructive`, `PUT` → `idempotent`.
548
+
549
+ Runtime proxy mode with `loadOpenAPI()` for instant prototyping — no code generation step.
550
+
551
+ ### Prisma → MCP with Field-Level Security
552
+
553
+ A Prisma Generator that produces Vurb.ts tools and Presenters with field-level security, tenant isolation, and OOM protection:
554
+
555
+ ```prisma
556
+ generator mcp {
557
+ provider = "vurb-prisma-gen"
558
+ output = "../src/tools/database"
559
+ }
560
+
561
+ model User {
562
+ id String @id @default(uuid())
563
+ email String @unique
564
+ passwordHash String /// @vurb.hide ← physically excluded from schema
565
+ stripeToken String /// @vurb.hide ← physically excluded from schema
566
+ creditScore Int /// @vurb.describe("Score 0-1000. Above 700 is PREMIUM.")
567
+ tenantId String /// @vurb.tenantKey ← injected into every WHERE clause
568
+ }
569
+ ```
570
+
571
+ `npx prisma generate` → typed CRUD tools with pagination capped at 50, tenant isolation at the generated code level. Cross-tenant access is structurally impossible.
572
+
573
+ ### n8n Workflows → MCP Tools
574
+
575
+ Auto-discover n8n webhook workflows as MCP tools with tag filtering, live polling, and MVA interception:
576
+
577
+ ```typescript
578
+ const n8n = await createN8nConnector({
579
+ url: process.env.N8N_URL!,
580
+ apiKey: process.env.N8N_API_KEY!,
581
+ includeTags: ['ai-enabled'],
582
+ pollInterval: 60_000,
583
+ onChange: () => server.notification({ method: 'notifications/tools/list_changed' }),
584
+ });
585
+ ```
586
+
587
+ n8n handles the Stripe/Salesforce/webhook logic. Vurb.ts provides typing, Presenters, middleware, and access control.
588
+
589
+ ---
590
+
591
+ ## Inspector — Real-Time Dashboard
592
+
593
+ ```bash
594
+ vurb inspect # Auto-discover and connect
595
+ vurb inspect --demo # Built-in simulator
596
+ ```
597
+
598
+ ```
599
+ ┌──────────────────────────────────────────────────────────────┐
600
+ │ ● LIVE: PID 12345 │ RAM: [█████░░░] 28MB │ UP: 01:23 │
601
+ ├───────────────────────┬──────────────────────────────────────┤
602
+ │ TOOL LIST │ X-RAY: billing.create_invoice │
603
+ │ ✓ billing.create │ LATE GUILLOTINE: │
604
+ │ ✓ billing.get │ DB Raw : 4.2KB │
605
+ │ ✗ users.delete │ Wire : 1.1KB │
606
+ │ ✓ system.health │ SAVINGS : ████████░░ 73.8% │
607
+ ├───────────────────────┴──────────────────────────────────────┤
608
+ │ 19:32:01 ROUTE billing.create │ 19:32:01 EXEC ✓ 45ms│
609
+ └──────────────────────────────────────────────────────────────┘
610
+ ```
611
+
612
+ Connects via **Shadow Socket** (Named Pipe / Unix Domain Socket) — no stdio interference, no port conflicts. Real-time tool list, request stream, Late Guillotine visualization.
613
+
614
+ ---
615
+
616
+ ## Testing — Full Pipeline in RAM
617
+
618
+ `@vurb/testing` runs the actual execution pipeline — same code path as production — and returns `MvaTestResult` with each MVA layer decomposed:
619
+
620
+ ```typescript
621
+ import { createVurbTester } from '@vurb/testing';
622
+
623
+ const tester = createVurbTester(registry, {
624
+ contextFactory: () => ({ prisma: mockPrisma, tenantId: 't_42', role: 'ADMIN' }),
625
+ });
626
+
627
+ describe('SOC2 Data Governance', () => {
628
+ it('strips PII before it reaches the LLM', async () => {
629
+ const result = await tester.callAction('db_user', 'find_many', { take: 10 });
630
+ for (const user of result.data) {
631
+ expect(user).not.toHaveProperty('passwordHash');
632
+ expect(user).not.toHaveProperty('tenantId');
633
+ }
634
+ });
635
+
636
+ it('sends governance rules with data', async () => {
637
+ const result = await tester.callAction('db_user', 'find_many', { take: 5 });
638
+ expect(result.systemRules).toContain('Email addresses are PII.');
639
+ });
640
+
641
+ it('blocks guest access', async () => {
642
+ const result = await tester.callAction('db_user', 'find_many', { take: 5 }, { role: 'GUEST' });
643
+ expect(result.isError).toBe(true);
644
+ });
645
+ });
646
+ ```
647
+
648
+ Assert every MVA layer: `result.data` (egress firewall), `result.systemRules` (JIT rules), `result.uiBlocks` (server-rendered charts), `result.data.length` (cognitive guardrail), `rawResponse` (HATEOAS hints). Works with Vitest, Jest, Mocha, or `node:test`.
649
+
650
+ ---
651
+
652
+ ## Deploy Anywhere
653
+
654
+ Every tool is transport-agnostic. Same code on Stdio, SSE, and serverless:
655
+
656
+ ### Vercel Functions
657
+
658
+ ```typescript
659
+ import { vercelAdapter } from '@vurb/vercel';
660
+ export const POST = vercelAdapter({ registry, contextFactory });
661
+ export const runtime = 'edge'; // global edge distribution
662
+ ```
663
+
664
+ ### Cloudflare Workers
665
+
666
+ ```typescript
667
+ import { cloudflareWorkersAdapter } from '@vurb/cloudflare';
668
+ export default cloudflareWorkersAdapter({ registry, contextFactory });
669
+ // D1 for edge-native SQL, KV for sub-ms reads, waitUntil for telemetry
670
+ ```
671
+
672
+ ---
673
+
674
+ ## Ecosystem
675
+
676
+ ### Adapters
677
+
678
+ | Package | Target |
679
+ |---|---|
680
+ | [`@vurb/vercel`](https://vurb.vinkius.com/vercel-adapter) | Vercel Functions (Edge / Node.js) |
681
+ | [`@vurb/cloudflare`](https://vurb.vinkius.com/cloudflare-adapter) | Cloudflare Workers — zero polyfills |
682
+
683
+ ### Generators & Connectors
684
+
685
+ | Package | Purpose |
686
+ |---|---|
687
+ | [`@vurb/openapi-gen`](https://vurb.vinkius.com/openapi-gen) | Generate typed tools from OpenAPI 3.x / Swagger 2.0 specs |
688
+ | [`@vurb/prisma-gen`](https://vurb.vinkius.com/prisma-gen) | Generate CRUD tools with field-level security from Prisma |
689
+ | [`@vurb/n8n`](https://vurb.vinkius.com/n8n-connector) | Auto-discover n8n workflows as MCP tools |
690
+ | [`@vurb/aws`](https://vurb.vinkius.com/aws-connector) | Auto-discover AWS Lambda & Step Functions |
691
+ | [`@vurb/skills`](https://vurb.vinkius.com/skills) | Progressive instruction distribution for agents |
692
+
693
+ ### Security & Auth
694
+
695
+ | Package | Purpose |
696
+ |---|---|
697
+ | [`@vurb/oauth`](https://vurb.vinkius.com/oauth) | RFC 8628 Device Flow authentication |
698
+ | [`@vurb/jwt`](https://vurb.vinkius.com/jwt) | JWT verification — HS256/RS256/ES256 + JWKS |
699
+ | [`@vurb/api-key`](https://vurb.vinkius.com/api-key) | API key validation with timing-safe comparison |
700
+
701
+ ### Developer Experience
702
+
703
+ | Package | Purpose |
704
+ |---|---|
705
+ | [`@vurb/testing`](https://vurb.vinkius.com/testing) | In-memory pipeline testing with MVA layer assertions |
706
+ | [`@vurb/inspector`](https://vurb.vinkius.com/inspector) | Real-time terminal dashboard via Shadow Socket |
707
+
708
+ ---
709
+
710
+ ## Documentation
711
+
712
+ Full guides, API reference, and cookbook recipes:
713
+
714
+ **[Vurb.ts.vinkius.com](https://vurb.vinkius.com/)**
715
+
716
+ ## Contributing
717
+
718
+ See [CONTRIBUTING.md](https://github.com/vinkius-labs/vurb.ts/blob/main/CONTRIBUTING.md) for development setup and PR guidelines.
719
+
720
+ ## Security
721
+
722
+ See [SECURITY.md](https://github.com/vinkius-labs/vurb.ts/blob/main/SECURITY.md) for reporting vulnerabilities.
723
+
724
+ ## License
725
+
726
+ [Apache 2.0](https://github.com/vinkius-labs/vurb.ts/blob/main/LICENSE)