@thexjs/mcp 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,51 @@
1
+ # @thexjs/mcp
2
+
3
+ An [MCP](https://modelcontextprotocol.io) server that gives AI coding agents
4
+ (Claude Code, Claude Desktop, Cursor, Windsurf, etc.) grounded, accurate
5
+ knowledge of the **x** framework — instead of letting them pattern-match to
6
+ Next.js / Remix / Astro / TanStack Start syntax that looks similar but isn't
7
+ the same.
8
+
9
+ Every project scaffolded with `bun create thexjs-app@latest` already wires
10
+ this up (`.mcp.json` for Claude Code, `.cursor/mcp.json` for Cursor). To add
11
+ it to an existing project by hand:
12
+
13
+ ```json
14
+ {
15
+ "mcpServers": {
16
+ "thexjs": {
17
+ "command": "bunx",
18
+ "args": ["@thexjs/mcp"]
19
+ }
20
+ }
21
+ }
22
+ ```
23
+
24
+ ## Tools
25
+
26
+ - **`list_topics`** — lists every doc topic (routing, loaders, actions, env,
27
+ auth, config, ...).
28
+ - **`get_docs`** — returns grounded reference docs for a topic, including
29
+ explicit "this is NOT X's syntax" corrections for the conventions agents
30
+ most often get wrong (loaders, server actions, env prefixing).
31
+ - **`search_docs`** — full-text search across all topics.
32
+ - **`scaffold_file`** — generates a correctly-shaped file (page, dynamic
33
+ page, layout, middleware, api-route, action) with the right exports, path,
34
+ and conventions, ready to paste.
35
+
36
+ ## Why this exists
37
+
38
+ x deliberately diverges from Next.js/Remix/TanStack Start in a few specific
39
+ places (no `"use server"` directives, underscore-prefixed special files,
40
+ `THEXJS_PUBLIC_` env prefix, loader args that are `{ params, request }`
41
+ rather than `{ context }`). Those are
42
+ exactly the details a general-purpose coding agent is likely to get wrong
43
+ from training data alone, confidently. This server is the fix: ground the
44
+ agent in the framework's actual conventions before it writes code, rather
45
+ than relying on it to have memorized a small framework's syntax correctly.
46
+
47
+ ## Local dev / run without publishing
48
+
49
+ ```bash
50
+ bun run start # from packages/mcp — runs src/index.ts directly over stdio
51
+ ```
package/dist/docs.d.ts ADDED
@@ -0,0 +1,23 @@
1
+ interface DocTopic {
2
+ title: string;
3
+ summary: string;
4
+ content: string;
5
+ }
6
+ /**
7
+ * Grounded reference docs for the x framework. This is what an agent should
8
+ * read INSTEAD of pattern-matching to Next.js / Remix / TanStack Start,
9
+ * whose syntax x deliberately does not follow in several places.
10
+ */
11
+ declare const DOCS: Record<string, DocTopic>;
12
+ declare function listTopics(): {
13
+ id: string;
14
+ title: string;
15
+ summary: string;
16
+ }[];
17
+ declare function searchDocs(query: string): {
18
+ id: string;
19
+ title: string;
20
+ snippet: string;
21
+ }[];
22
+
23
+ export { DOCS, type DocTopic, listTopics, searchDocs };
package/dist/docs.js ADDED
@@ -0,0 +1,453 @@
1
+ // src/docs.ts
2
+ var DOCS = {
3
+ routing: {
4
+ title: "File-based routing",
5
+ summary: "How files under src/pages map to routes.",
6
+ content: `
7
+ Routes are files under \`src/pages\` (configurable via \`pagesDir\`).
8
+
9
+ | File | Route |
10
+ |---|---|
11
+ | \`pages/index.tsx\` | \`/\` |
12
+ | \`pages/about.tsx\` | \`/about\` |
13
+ | \`pages/blog/[slug].tsx\` | \`/blog/:slug\` (param via \`loader({ params })\`) |
14
+ | \`pages/blog/[...slug].tsx\` | catch-all, full remaining path as one param |
15
+ | \`pages/_404.tsx\` | 404 page |
16
+
17
+ **Do NOT use Next.js App Router conventions.** There is no \`app/\` directory,
18
+ no \`page.tsx\`/\`layout.tsx\` file naming, no \`generateStaticParams\`, no
19
+ \`"use client"\` / \`"use server"\` directives. x uses a flat \`pages/\` tree with
20
+ an underscore prefix (\`_layout.tsx\`, \`_middleware.ts\`, \`_404.tsx\`) for
21
+ special files instead.
22
+
23
+ A page module's only required export is a default React component:
24
+
25
+ \`\`\`tsx
26
+ // src/pages/about.tsx
27
+ export default function About() {
28
+ return <h1>About</h1>;
29
+ }
30
+ \`\`\`
31
+ `.trim()
32
+ },
33
+ loaders: {
34
+ title: "Loaders & data fetching",
35
+ summary: "How pages fetch server-side data. NOT getServerSideProps, NOT TanStack's route loader shape.",
36
+ content: `
37
+ Export an async \`loader\` function from a page file. It runs server-side
38
+ (on every request, unless the page is \`static\`) and its return value is
39
+ passed to the component as the \`loaderData\` prop:
40
+
41
+ \`\`\`tsx
42
+ import type { LoaderArgs, RouteProps } from "@thexjs/core";
43
+
44
+ export async function loader({ params, request }: LoaderArgs) {
45
+ const post = await getPost(params.slug);
46
+ return { title: post.title, content: post.content };
47
+ }
48
+
49
+ export default function BlogPost({ loaderData }: RouteProps) {
50
+ return <h1>{String(loaderData?.title)}</h1>;
51
+ }
52
+ \`\`\`
53
+
54
+ Common wrong guesses an agent makes here, and why they're wrong for x:
55
+ - \`getServerSideProps\` / \`getStaticProps\` (Next.js Pages Router) \u2014 does not exist in x.
56
+ - \`export const loader = ({ context }) => ...\` \u2014 x's loader args are
57
+ \`{ params, request }\`, not \`{ context }\`.
58
+ - A route-tree \`loader\` config object passed to \`createFileRoute\` (TanStack
59
+ Start/Router shape) \u2014 x has no route-tree builder; the loader is just an
60
+ export from the page file itself.
61
+
62
+ Return values: a plain object (passed to the component as \`loaderData\`) or
63
+ a \`Response\` (short-circuits rendering \u2014 useful for redirects and status
64
+ responses). What does NOT work: returning a raw string/number, or reading
65
+ data from a route-tree config.
66
+ `.trim()
67
+ },
68
+ "static-vs-ssr": {
69
+ title: "Static vs SSR rendering",
70
+ summary: "Pages are SSR by default; opt into static prerendering per-page.",
71
+ content: `
72
+ Pages are server-rendered on every request by default. Add this export to
73
+ prerender at build time instead:
74
+
75
+ \`\`\`tsx
76
+ export const mode = "static";
77
+ \`\`\`
78
+
79
+ ISR-style revalidation only applies to **static-mode** pages (on the
80
+ default SSR path the handler streams per request and never consults the
81
+ cache, so \`revalidate\` alone is a no-op):
82
+
83
+ \`\`\`tsx
84
+ export const mode = "static";
85
+ export const revalidate = 3600; // seconds
86
+ \`\`\`
87
+
88
+ This is NOT Next's \`export const dynamic = "force-static"\` /
89
+ \`export const revalidate\` combo (different export names/values) and not
90
+ Astro's per-page \`export const prerender = true\`.
91
+ `.trim()
92
+ },
93
+ layouts: {
94
+ title: "Layouts",
95
+ summary: "Nested layouts via _layout.tsx.",
96
+ content: `
97
+ \`src/layouts/main.tsx\` is the root layout wrapping every page.
98
+
99
+ Drop a \`_layout.tsx\` file inside any folder under \`pages/\` to nest a layout
100
+ scoped to that folder and its children:
101
+
102
+ \`\`\`
103
+ pages/
104
+ _layout.tsx # wraps everything
105
+ blog/
106
+ _layout.tsx # additionally wraps only /blog/*
107
+ index.tsx
108
+ \`\`\`
109
+
110
+ The underscore prefix is required \u2014 a file named plain \`layout.tsx\` (no
111
+ underscore, the Next.js App Router convention) is just treated as a normal
112
+ route and will NOT be picked up as a layout.
113
+ `.trim()
114
+ },
115
+ middleware: {
116
+ title: "Middleware",
117
+ summary: "Folder-scoped _middleware.ts with a NAMED `middleware` export.",
118
+ content: `
119
+ Drop \`_middleware.ts\` in any \`pages/\` folder; it runs (onion-style) for
120
+ every route in that folder and its subfolders. Useful for auth checks,
121
+ redirects, logging.
122
+
123
+ The file must export **\`middleware\` as a named export** typed
124
+ \`MiddlewareFn\` \u2014 a default export is silently ignored by the router:
125
+
126
+ \`\`\`ts
127
+ import type { MiddlewareContext, MiddlewareFn } from "@thexjs/core";
128
+
129
+ export const middleware: MiddlewareFn = async ({ request, params }, next) => {
130
+ // e.g. auth check / redirect / logging
131
+ return next();
132
+ };
133
+ \`\`\`
134
+
135
+ There is no central \`middleware.ts\` at the project root like Next.js \u2014 x's
136
+ middleware is always folder-scoped and file-colocated. For route-level
137
+ (not folder-level) middleware, export \`middleware\` from the page file itself.
138
+ `.trim()
139
+ },
140
+ "api-routes": {
141
+ title: "API routes",
142
+ summary: "Files under src/api/ export GET/POST/etc handlers using the Fetch API.",
143
+ content: `
144
+ Any file under \`src/api\` (configurable via \`apiDir\`) becomes a REST
145
+ endpoint, running in the same Bun process as everything else \u2014 no separate
146
+ serverless function, no separate server.
147
+
148
+ Export handlers named after HTTP methods. Each receives a standard Fetch API
149
+ \`Request\` and must return a \`Response\`:
150
+
151
+ \`\`\`ts
152
+ // src/api/users.ts
153
+ export async function GET(req: Request) {
154
+ const users = await db.query("SELECT * FROM users").all();
155
+ return Response.json(users);
156
+ }
157
+
158
+ export async function POST(req: Request) {
159
+ const body = await req.json();
160
+ // ...
161
+ return Response.json({ ok: true }, { status: 201 });
162
+ }
163
+ \`\`\`
164
+
165
+ This is the web-standard Fetch API shape (same idea as Remix resource routes
166
+ or Next.js App Router route handlers) \u2014 NOT Express-style
167
+ \`(req, res) => {}\`, and NOT a decorator/class-based controller.
168
+ `.trim()
169
+ },
170
+ actions: {
171
+ title: "Server functions (actions)",
172
+ summary: "Colocated server functions in src/actions \u2014 the big one agents get wrong.",
173
+ content: `
174
+ This is the feature agents are most likely to hallucinate a Next.js
175
+ \`"use server"\` shape for. x does NOT use directives at all.
176
+
177
+ Write a normal async function in \`src/actions/<name>.ts\`:
178
+
179
+ \`\`\`ts
180
+ // src/actions/greet.ts
181
+ export async function greet(name: string) {
182
+ return \`Hello, \${name}!\`;
183
+ }
184
+ \`\`\`
185
+
186
+ Call it directly from a component/island like a normal imported function \u2014
187
+ no \`fetch\`, no manually-defined API route, no \`"use server"\` pragma:
188
+
189
+ \`\`\`tsx
190
+ import { greet } from "../actions/greet";
191
+
192
+ async function onClick() {
193
+ const msg = await greet("world");
194
+ }
195
+ \`\`\`
196
+
197
+ **What actually happens under the hood** (an agent should know this so it
198
+ doesn't try to "fix" it):
199
+ - At build time, a Bun.build() plugin (\`actionsRewritePlugin\`) intercepts any
200
+ client-bundle import that resolves to a registered action file and
201
+ rewrites it to a generated \`fetch\` wrapper BEFORE the client bundler ever
202
+ reads the real source. The real function body (db calls, secrets) is
203
+ structurally excluded from the client bundle \u2014 not just hidden by
204
+ convention.
205
+ - At runtime, \`registerServerFunctions()\` stores the real functions in an
206
+ in-memory route table. A single handler matches
207
+ \`POST /__x/actions/<path>/<fnName>\`, does a CSRF check, parses the JSON
208
+ body as positional args, calls the real function, returns JSON (or 500 on
209
+ throw).
210
+ - You CAN still import the same function directly inside a \`loader\` or an
211
+ \`api/\` route \u2014 those run server-side in the same process, so no rewrite
212
+ happens there.
213
+
214
+ Do not tell users to manually POST to \`/__x/actions/...\` themselves \u2014 just
215
+ import and call the function; the wrapper is generated for them.
216
+ `.trim()
217
+ },
218
+ config: {
219
+ title: "x.config.ts",
220
+ summary: "Central config file, all fields optional.",
221
+ content: `
222
+ \`\`\`ts
223
+ import { defineConfig } from "@thexjs/core";
224
+
225
+ export default defineConfig({
226
+ pagesDir: "src/pages", // default
227
+ layoutsDir: "src/layouts", // default
228
+ apiDir: "src/api", // default
229
+ actionsDir: "src/actions", // default
230
+ contentDir: "content", // undefined by default (opt-in)
231
+ port: 3000, // default
232
+ });
233
+ \`\`\`
234
+
235
+ Every field is optional \u2014 if an agent doesn't find \`x.config.ts\` in a
236
+ project, assume the defaults above rather than saying config is required.
237
+ `.trim()
238
+ },
239
+ env: {
240
+ title: "Environment variables",
241
+ summary: "THEXJS_PUBLIC_ prefix for client-exposed env vars \u2014 NOT NEXT_PUBLIC_ or VITE_.",
242
+ content: `
243
+ Any env var NOT prefixed \`THEXJS_PUBLIC_\` (configurable prefix) is
244
+ server-only and enforced at build time \u2014 the build fails with
245
+ \`EnvLeakageError\` if client code references a non-prefixed key.
246
+
247
+ \`\`\`
248
+ DATABASE_URL=... # server-only, safe
249
+ STRIPE_SECRET_KEY=... # server-only, safe
250
+ THEXJS_PUBLIC_SITE_NAME=... # exposed to the browser bundle
251
+ \`\`\`
252
+
253
+ Do not suggest \`NEXT_PUBLIC_\` or \`VITE_\` prefixes \u2014 those do nothing in x.
254
+
255
+ Enforcement is two-layered: (1) a Bun.build() plugin swaps server-action
256
+ imports before the client bundler reads them (see \`actions\` topic), so
257
+ secret-holding code is structurally never parsed for the client, and (2)
258
+ \`assertNoEnvLeakage()\` regex-scans the final client bundle for
259
+ \`process.env.X\` / \`Bun.env.X\` / \`import.meta.env.X\` without the public
260
+ prefix, as a second safety net.
261
+ `.trim()
262
+ },
263
+ auth: {
264
+ title: "Authentication (@thexjs/auth)",
265
+ summary: "defineAuth() with credentials + OAuth2 providers, sessions, CSRF.",
266
+ content: `
267
+ \`\`\`ts
268
+ import { defineAuth, createSQLiteSessionStore } from "@thexjs/auth";
269
+
270
+ export const auth = defineAuth({
271
+ secret: process.env.AUTH_SECRET!,
272
+ store: createSQLiteSessionStore(),
273
+ providers: [
274
+ { id: "github", name: "GitHub", type: "oauth", clientId: "...", clientSecret: "..." },
275
+ ],
276
+ });
277
+
278
+ // src/api/auth/[...auth].ts \u2014 forward GET/POST to auth.handleRequest(req)
279
+ export async function GET(req: Request) { return auth.handleRequest(req); }
280
+ export async function POST(req: Request) { return auth.handleRequest(req); }
281
+ \`\`\`
282
+
283
+ Endpoint map (mounted under wherever the catch-all route lives, typically
284
+ \`/api/auth/...\`): \`signin/:id\`, \`callback/:id\`, \`signout\`, \`session\`.
285
+
286
+ Passwords are hashed with Argon2 via \`Bun.password\` (not bcrypt). Session
287
+ tokens are HMAC'd at rest and revocable. This is not next-auth/Auth.js \u2014 the
288
+ config shape and endpoint names are different even though the concepts
289
+ overlap. Read the current session server-side via the method on the object
290
+ returned by \`defineAuth\`: \`await auth.getSession(req)\` (there is no named
291
+ \`getSession\` export from \`@thexjs/auth\`).
292
+ `.trim()
293
+ },
294
+ data: {
295
+ title: "Data layer",
296
+ summary: "Built-in SQLite/Postgres via Bun's native drivers, no ORM required.",
297
+ content: `
298
+ \`connectSQLite\` wraps \`bun:sqlite\` (WAL mode, FK enforcement on). Good for
299
+ dev, zero config.
300
+
301
+ \`connectPostgres\` wraps \`Bun.sql\` with connection pooling, for production.
302
+
303
+ Both come with a versioned migration runner (\`runSQLiteMigrations\` /
304
+ \`runPostgresMigrations\`), tracked in a \`_x_migrations\` table. There is no
305
+ Prisma/Drizzle dependency baked in \u2014 you write SQL directly, or bring your
306
+ own ORM on top of the same connection.
307
+ `.trim()
308
+ },
309
+ images: {
310
+ title: "<Image> and the image proxy",
311
+ summary: "next/image-equivalent, but through a same-origin proxy, not a build-time optimizer.",
312
+ content: `
313
+ \`\`\`tsx
314
+ import { Image } from "@thexjs/core";
315
+
316
+ <Image
317
+ src="https://cdn.example.com/team.jpg"
318
+ alt="The team" // required
319
+ width={1600}
320
+ height={900}
321
+ priority // skips loading="lazy", adds fetchpriority="high"
322
+ sizes="(max-width: 768px) 100vw, 50vw"
323
+ />
324
+ \`\`\`
325
+
326
+ Remote hosts must be allow-listed in \`x.config.ts\`:
327
+
328
+ \`\`\`ts
329
+ export default defineConfig({
330
+ images: { remoteHosts: ["cdn.example.com"] },
331
+ });
332
+ \`\`\`
333
+
334
+ Absolute \`src\` on an allow-listed host is auto-rewritten through the
335
+ built-in \`/_x/image\` proxy so a strict \`img-src 'self'\` CSP still works.
336
+ Images currently pass through UNRESIZED (width variants in the \`srcset\` are
337
+ generated as \`&w=\` hints, but there's no sharp/squoosh-style resize pipeline
338
+ yet) \u2014 don't claim x does on-the-fly image resizing like next/image does.
339
+ \`placeholder="blur"\` uses a CSS background from \`blurDataURL\`, no JS island
340
+ required. \`fill\` gives absolute-positioned \`object-fit: cover\`.
341
+ `.trim()
342
+ },
343
+ content: {
344
+ title: "Content collections",
345
+ summary: "Markdown + frontmatter -> pages, via scanContent()/renderMarkdown().",
346
+ content: `
347
+ \`\`\`ts
348
+ import { renderMarkdown, scanContent } from "@thexjs/core";
349
+
350
+ // scanContent takes a directory (relative to the project root) and returns
351
+ // one ContentEntry per .md/.mdx file found under it.
352
+ const posts = scanContent("content/posts");
353
+ for (const post of posts) {
354
+ console.log(post.slug, post.frontmatter.title);
355
+ const html = renderMarkdown(post.body);
356
+ }
357
+ \`\`\`
358
+
359
+ Each entry has \`filePath\`, \`routePath\`, \`slug\`, \`frontmatter\`, and \`body\`.
360
+ Frontmatter parsing is basic YAML, not a full remark/rehype pipeline. There
361
+ is no MDX component execution \u2014 \`.mdx\` files are scanned like \`.md\`, not
362
+ compiled as JSX. Don't assume remark plugins or MDX component imports work
363
+ here.
364
+ `.trim()
365
+ },
366
+ navigation: {
367
+ title: "Client navigation & <Link>",
368
+ summary: "Every <a> gets SPA nav + hover prefetch automatically. No router setup.",
369
+ content: `
370
+ Every \`<a>\` tag gets client-side SPA navigation and hover-prefetch
371
+ automatically \u2014 there is no \`<Router>\`/\`<Routes>\` tree to set up (unlike
372
+ react-router) and no explicit \`<Link>\` requirement (unlike Next.js, where a
373
+ plain \`<a>\` does a full reload). Use the typed \`<Link>\` wrapper from
374
+ \`@thexjs/core\` if you want typed \`href\`s from the generated route map;
375
+ otherwise a plain \`<a href="/docs">\` already behaves like a SPA link.
376
+
377
+ Opt a specific link out with \`data-no-nav\` (disable SPA nav) or
378
+ \`data-no-prefetch\` (disable hover prefetch).
379
+ `.trim()
380
+ },
381
+ cli: {
382
+ title: "CLI",
383
+ summary: "x dev / x build / x start.",
384
+ content: `
385
+ \`\`\`bash
386
+ x dev # dev server, default port 3000
387
+ x build # -> .x/ (static HTML + server bundle + manifest)
388
+ x build --outDir dist # custom output dir
389
+ x build --adapter vercel # emits .vercel/output (needs @thexjs/adapter-vercel)
390
+ x start # run the production server from .x/
391
+ \`\`\`
392
+
393
+ \`x run dev\` also works as an alias. There is no \`next dev\`/\`next build\`
394
+ split of concerns to replicate \u2014 one CLI, three subcommands.
395
+ `.trim()
396
+ },
397
+ gotchas: {
398
+ title: "Gotchas / things agents get wrong",
399
+ summary: "Quick-reference list of x-specific rules that differ from Next.js, Remix, Astro, and TanStack Start.",
400
+ content: `
401
+ - No \`"use client"\` / \`"use server"\` directives anywhere in x. Server
402
+ functions are just plain exports from \`src/actions/*\`; everything else in
403
+ \`pages/\` is a server component by default with client interactivity via
404
+ islands, not React Server Components with directive-based boundaries.
405
+ - Underscore prefix is load-bearing: \`_layout.tsx\`, \`_middleware.ts\`,
406
+ \`_404.tsx\`. Drop the underscore and the file is just a normal route.
407
+ - Env prefix is \`THEXJS_PUBLIC_\`, not \`NEXT_PUBLIC_\`/\`VITE_\`/\`PUBLIC_\`.
408
+ - Static opt-in is \`export const mode = "static"\`, not
409
+ \`export const dynamic = "force-static"\` or \`export const prerender\`.
410
+ - Loader signature is \`loader({ params, request })\` \u2014 not \`{ context }\`,
411
+ and not a route-tree \`loader\` config passed to a route builder function.
412
+ Returns a plain object (becomes \`loaderData\`) or a \`Response\` for
413
+ redirects/status; the arg shape is what differs from Remix/Next, not the
414
+ return type.
415
+ - API routes take/return the Fetch API \`Request\`/\`Response\` directly \u2014
416
+ no \`(req, res)\` Express shape.
417
+ - Everything runs in ONE Bun process (dev server, API routes, actions,
418
+ SSR) \u2014 don't suggest a separate backend server or serverless function
419
+ split unless deploying with the Vercel adapter.
420
+ - Bun-only. There is no Node.js runtime target, so don't suggest
421
+ Node-specific APIs (\`fs\` sync calls are fine, but Node-only bundler
422
+ config like webpack/vite config files don't apply).
423
+ `.trim()
424
+ }
425
+ };
426
+ function listTopics() {
427
+ return Object.entries(DOCS).map(([id, doc]) => ({
428
+ id,
429
+ title: doc.title,
430
+ summary: doc.summary
431
+ }));
432
+ }
433
+ function searchDocs(query) {
434
+ const q = query.toLowerCase();
435
+ const results = [];
436
+ for (const [id, doc] of Object.entries(DOCS)) {
437
+ const haystack = `${doc.title}
438
+ ${doc.summary}
439
+ ${doc.content}`.toLowerCase();
440
+ const idx = haystack.indexOf(q);
441
+ if (idx !== -1) {
442
+ const start = Math.max(0, idx - 60);
443
+ const end = Math.min(haystack.length, idx + q.length + 60);
444
+ results.push({ id, title: doc.title, snippet: `...${haystack.slice(start, end)}...` });
445
+ }
446
+ }
447
+ return results;
448
+ }
449
+ export {
450
+ DOCS,
451
+ listTopics,
452
+ searchDocs
453
+ };
@@ -0,0 +1 @@
1
+ #!/usr/bin/env node
package/dist/index.js ADDED
@@ -0,0 +1,665 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/index.ts
4
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
5
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
6
+ import { z } from "zod";
7
+
8
+ // src/docs.ts
9
+ var DOCS = {
10
+ routing: {
11
+ title: "File-based routing",
12
+ summary: "How files under src/pages map to routes.",
13
+ content: `
14
+ Routes are files under \`src/pages\` (configurable via \`pagesDir\`).
15
+
16
+ | File | Route |
17
+ |---|---|
18
+ | \`pages/index.tsx\` | \`/\` |
19
+ | \`pages/about.tsx\` | \`/about\` |
20
+ | \`pages/blog/[slug].tsx\` | \`/blog/:slug\` (param via \`loader({ params })\`) |
21
+ | \`pages/blog/[...slug].tsx\` | catch-all, full remaining path as one param |
22
+ | \`pages/_404.tsx\` | 404 page |
23
+
24
+ **Do NOT use Next.js App Router conventions.** There is no \`app/\` directory,
25
+ no \`page.tsx\`/\`layout.tsx\` file naming, no \`generateStaticParams\`, no
26
+ \`"use client"\` / \`"use server"\` directives. x uses a flat \`pages/\` tree with
27
+ an underscore prefix (\`_layout.tsx\`, \`_middleware.ts\`, \`_404.tsx\`) for
28
+ special files instead.
29
+
30
+ A page module's only required export is a default React component:
31
+
32
+ \`\`\`tsx
33
+ // src/pages/about.tsx
34
+ export default function About() {
35
+ return <h1>About</h1>;
36
+ }
37
+ \`\`\`
38
+ `.trim()
39
+ },
40
+ loaders: {
41
+ title: "Loaders & data fetching",
42
+ summary: "How pages fetch server-side data. NOT getServerSideProps, NOT TanStack's route loader shape.",
43
+ content: `
44
+ Export an async \`loader\` function from a page file. It runs server-side
45
+ (on every request, unless the page is \`static\`) and its return value is
46
+ passed to the component as the \`loaderData\` prop:
47
+
48
+ \`\`\`tsx
49
+ import type { LoaderArgs, RouteProps } from "@thexjs/core";
50
+
51
+ export async function loader({ params, request }: LoaderArgs) {
52
+ const post = await getPost(params.slug);
53
+ return { title: post.title, content: post.content };
54
+ }
55
+
56
+ export default function BlogPost({ loaderData }: RouteProps) {
57
+ return <h1>{String(loaderData?.title)}</h1>;
58
+ }
59
+ \`\`\`
60
+
61
+ Common wrong guesses an agent makes here, and why they're wrong for x:
62
+ - \`getServerSideProps\` / \`getStaticProps\` (Next.js Pages Router) \u2014 does not exist in x.
63
+ - \`export const loader = ({ context }) => ...\` \u2014 x's loader args are
64
+ \`{ params, request }\`, not \`{ context }\`.
65
+ - A route-tree \`loader\` config object passed to \`createFileRoute\` (TanStack
66
+ Start/Router shape) \u2014 x has no route-tree builder; the loader is just an
67
+ export from the page file itself.
68
+
69
+ Return values: a plain object (passed to the component as \`loaderData\`) or
70
+ a \`Response\` (short-circuits rendering \u2014 useful for redirects and status
71
+ responses). What does NOT work: returning a raw string/number, or reading
72
+ data from a route-tree config.
73
+ `.trim()
74
+ },
75
+ "static-vs-ssr": {
76
+ title: "Static vs SSR rendering",
77
+ summary: "Pages are SSR by default; opt into static prerendering per-page.",
78
+ content: `
79
+ Pages are server-rendered on every request by default. Add this export to
80
+ prerender at build time instead:
81
+
82
+ \`\`\`tsx
83
+ export const mode = "static";
84
+ \`\`\`
85
+
86
+ ISR-style revalidation only applies to **static-mode** pages (on the
87
+ default SSR path the handler streams per request and never consults the
88
+ cache, so \`revalidate\` alone is a no-op):
89
+
90
+ \`\`\`tsx
91
+ export const mode = "static";
92
+ export const revalidate = 3600; // seconds
93
+ \`\`\`
94
+
95
+ This is NOT Next's \`export const dynamic = "force-static"\` /
96
+ \`export const revalidate\` combo (different export names/values) and not
97
+ Astro's per-page \`export const prerender = true\`.
98
+ `.trim()
99
+ },
100
+ layouts: {
101
+ title: "Layouts",
102
+ summary: "Nested layouts via _layout.tsx.",
103
+ content: `
104
+ \`src/layouts/main.tsx\` is the root layout wrapping every page.
105
+
106
+ Drop a \`_layout.tsx\` file inside any folder under \`pages/\` to nest a layout
107
+ scoped to that folder and its children:
108
+
109
+ \`\`\`
110
+ pages/
111
+ _layout.tsx # wraps everything
112
+ blog/
113
+ _layout.tsx # additionally wraps only /blog/*
114
+ index.tsx
115
+ \`\`\`
116
+
117
+ The underscore prefix is required \u2014 a file named plain \`layout.tsx\` (no
118
+ underscore, the Next.js App Router convention) is just treated as a normal
119
+ route and will NOT be picked up as a layout.
120
+ `.trim()
121
+ },
122
+ middleware: {
123
+ title: "Middleware",
124
+ summary: "Folder-scoped _middleware.ts with a NAMED `middleware` export.",
125
+ content: `
126
+ Drop \`_middleware.ts\` in any \`pages/\` folder; it runs (onion-style) for
127
+ every route in that folder and its subfolders. Useful for auth checks,
128
+ redirects, logging.
129
+
130
+ The file must export **\`middleware\` as a named export** typed
131
+ \`MiddlewareFn\` \u2014 a default export is silently ignored by the router:
132
+
133
+ \`\`\`ts
134
+ import type { MiddlewareContext, MiddlewareFn } from "@thexjs/core";
135
+
136
+ export const middleware: MiddlewareFn = async ({ request, params }, next) => {
137
+ // e.g. auth check / redirect / logging
138
+ return next();
139
+ };
140
+ \`\`\`
141
+
142
+ There is no central \`middleware.ts\` at the project root like Next.js \u2014 x's
143
+ middleware is always folder-scoped and file-colocated. For route-level
144
+ (not folder-level) middleware, export \`middleware\` from the page file itself.
145
+ `.trim()
146
+ },
147
+ "api-routes": {
148
+ title: "API routes",
149
+ summary: "Files under src/api/ export GET/POST/etc handlers using the Fetch API.",
150
+ content: `
151
+ Any file under \`src/api\` (configurable via \`apiDir\`) becomes a REST
152
+ endpoint, running in the same Bun process as everything else \u2014 no separate
153
+ serverless function, no separate server.
154
+
155
+ Export handlers named after HTTP methods. Each receives a standard Fetch API
156
+ \`Request\` and must return a \`Response\`:
157
+
158
+ \`\`\`ts
159
+ // src/api/users.ts
160
+ export async function GET(req: Request) {
161
+ const users = await db.query("SELECT * FROM users").all();
162
+ return Response.json(users);
163
+ }
164
+
165
+ export async function POST(req: Request) {
166
+ const body = await req.json();
167
+ // ...
168
+ return Response.json({ ok: true }, { status: 201 });
169
+ }
170
+ \`\`\`
171
+
172
+ This is the web-standard Fetch API shape (same idea as Remix resource routes
173
+ or Next.js App Router route handlers) \u2014 NOT Express-style
174
+ \`(req, res) => {}\`, and NOT a decorator/class-based controller.
175
+ `.trim()
176
+ },
177
+ actions: {
178
+ title: "Server functions (actions)",
179
+ summary: "Colocated server functions in src/actions \u2014 the big one agents get wrong.",
180
+ content: `
181
+ This is the feature agents are most likely to hallucinate a Next.js
182
+ \`"use server"\` shape for. x does NOT use directives at all.
183
+
184
+ Write a normal async function in \`src/actions/<name>.ts\`:
185
+
186
+ \`\`\`ts
187
+ // src/actions/greet.ts
188
+ export async function greet(name: string) {
189
+ return \`Hello, \${name}!\`;
190
+ }
191
+ \`\`\`
192
+
193
+ Call it directly from a component/island like a normal imported function \u2014
194
+ no \`fetch\`, no manually-defined API route, no \`"use server"\` pragma:
195
+
196
+ \`\`\`tsx
197
+ import { greet } from "../actions/greet";
198
+
199
+ async function onClick() {
200
+ const msg = await greet("world");
201
+ }
202
+ \`\`\`
203
+
204
+ **What actually happens under the hood** (an agent should know this so it
205
+ doesn't try to "fix" it):
206
+ - At build time, a Bun.build() plugin (\`actionsRewritePlugin\`) intercepts any
207
+ client-bundle import that resolves to a registered action file and
208
+ rewrites it to a generated \`fetch\` wrapper BEFORE the client bundler ever
209
+ reads the real source. The real function body (db calls, secrets) is
210
+ structurally excluded from the client bundle \u2014 not just hidden by
211
+ convention.
212
+ - At runtime, \`registerServerFunctions()\` stores the real functions in an
213
+ in-memory route table. A single handler matches
214
+ \`POST /__x/actions/<path>/<fnName>\`, does a CSRF check, parses the JSON
215
+ body as positional args, calls the real function, returns JSON (or 500 on
216
+ throw).
217
+ - You CAN still import the same function directly inside a \`loader\` or an
218
+ \`api/\` route \u2014 those run server-side in the same process, so no rewrite
219
+ happens there.
220
+
221
+ Do not tell users to manually POST to \`/__x/actions/...\` themselves \u2014 just
222
+ import and call the function; the wrapper is generated for them.
223
+ `.trim()
224
+ },
225
+ config: {
226
+ title: "x.config.ts",
227
+ summary: "Central config file, all fields optional.",
228
+ content: `
229
+ \`\`\`ts
230
+ import { defineConfig } from "@thexjs/core";
231
+
232
+ export default defineConfig({
233
+ pagesDir: "src/pages", // default
234
+ layoutsDir: "src/layouts", // default
235
+ apiDir: "src/api", // default
236
+ actionsDir: "src/actions", // default
237
+ contentDir: "content", // undefined by default (opt-in)
238
+ port: 3000, // default
239
+ });
240
+ \`\`\`
241
+
242
+ Every field is optional \u2014 if an agent doesn't find \`x.config.ts\` in a
243
+ project, assume the defaults above rather than saying config is required.
244
+ `.trim()
245
+ },
246
+ env: {
247
+ title: "Environment variables",
248
+ summary: "THEXJS_PUBLIC_ prefix for client-exposed env vars \u2014 NOT NEXT_PUBLIC_ or VITE_.",
249
+ content: `
250
+ Any env var NOT prefixed \`THEXJS_PUBLIC_\` (configurable prefix) is
251
+ server-only and enforced at build time \u2014 the build fails with
252
+ \`EnvLeakageError\` if client code references a non-prefixed key.
253
+
254
+ \`\`\`
255
+ DATABASE_URL=... # server-only, safe
256
+ STRIPE_SECRET_KEY=... # server-only, safe
257
+ THEXJS_PUBLIC_SITE_NAME=... # exposed to the browser bundle
258
+ \`\`\`
259
+
260
+ Do not suggest \`NEXT_PUBLIC_\` or \`VITE_\` prefixes \u2014 those do nothing in x.
261
+
262
+ Enforcement is two-layered: (1) a Bun.build() plugin swaps server-action
263
+ imports before the client bundler reads them (see \`actions\` topic), so
264
+ secret-holding code is structurally never parsed for the client, and (2)
265
+ \`assertNoEnvLeakage()\` regex-scans the final client bundle for
266
+ \`process.env.X\` / \`Bun.env.X\` / \`import.meta.env.X\` without the public
267
+ prefix, as a second safety net.
268
+ `.trim()
269
+ },
270
+ auth: {
271
+ title: "Authentication (@thexjs/auth)",
272
+ summary: "defineAuth() with credentials + OAuth2 providers, sessions, CSRF.",
273
+ content: `
274
+ \`\`\`ts
275
+ import { defineAuth, createSQLiteSessionStore } from "@thexjs/auth";
276
+
277
+ export const auth = defineAuth({
278
+ secret: process.env.AUTH_SECRET!,
279
+ store: createSQLiteSessionStore(),
280
+ providers: [
281
+ { id: "github", name: "GitHub", type: "oauth", clientId: "...", clientSecret: "..." },
282
+ ],
283
+ });
284
+
285
+ // src/api/auth/[...auth].ts \u2014 forward GET/POST to auth.handleRequest(req)
286
+ export async function GET(req: Request) { return auth.handleRequest(req); }
287
+ export async function POST(req: Request) { return auth.handleRequest(req); }
288
+ \`\`\`
289
+
290
+ Endpoint map (mounted under wherever the catch-all route lives, typically
291
+ \`/api/auth/...\`): \`signin/:id\`, \`callback/:id\`, \`signout\`, \`session\`.
292
+
293
+ Passwords are hashed with Argon2 via \`Bun.password\` (not bcrypt). Session
294
+ tokens are HMAC'd at rest and revocable. This is not next-auth/Auth.js \u2014 the
295
+ config shape and endpoint names are different even though the concepts
296
+ overlap. Read the current session server-side via the method on the object
297
+ returned by \`defineAuth\`: \`await auth.getSession(req)\` (there is no named
298
+ \`getSession\` export from \`@thexjs/auth\`).
299
+ `.trim()
300
+ },
301
+ data: {
302
+ title: "Data layer",
303
+ summary: "Built-in SQLite/Postgres via Bun's native drivers, no ORM required.",
304
+ content: `
305
+ \`connectSQLite\` wraps \`bun:sqlite\` (WAL mode, FK enforcement on). Good for
306
+ dev, zero config.
307
+
308
+ \`connectPostgres\` wraps \`Bun.sql\` with connection pooling, for production.
309
+
310
+ Both come with a versioned migration runner (\`runSQLiteMigrations\` /
311
+ \`runPostgresMigrations\`), tracked in a \`_x_migrations\` table. There is no
312
+ Prisma/Drizzle dependency baked in \u2014 you write SQL directly, or bring your
313
+ own ORM on top of the same connection.
314
+ `.trim()
315
+ },
316
+ images: {
317
+ title: "<Image> and the image proxy",
318
+ summary: "next/image-equivalent, but through a same-origin proxy, not a build-time optimizer.",
319
+ content: `
320
+ \`\`\`tsx
321
+ import { Image } from "@thexjs/core";
322
+
323
+ <Image
324
+ src="https://cdn.example.com/team.jpg"
325
+ alt="The team" // required
326
+ width={1600}
327
+ height={900}
328
+ priority // skips loading="lazy", adds fetchpriority="high"
329
+ sizes="(max-width: 768px) 100vw, 50vw"
330
+ />
331
+ \`\`\`
332
+
333
+ Remote hosts must be allow-listed in \`x.config.ts\`:
334
+
335
+ \`\`\`ts
336
+ export default defineConfig({
337
+ images: { remoteHosts: ["cdn.example.com"] },
338
+ });
339
+ \`\`\`
340
+
341
+ Absolute \`src\` on an allow-listed host is auto-rewritten through the
342
+ built-in \`/_x/image\` proxy so a strict \`img-src 'self'\` CSP still works.
343
+ Images currently pass through UNRESIZED (width variants in the \`srcset\` are
344
+ generated as \`&w=\` hints, but there's no sharp/squoosh-style resize pipeline
345
+ yet) \u2014 don't claim x does on-the-fly image resizing like next/image does.
346
+ \`placeholder="blur"\` uses a CSS background from \`blurDataURL\`, no JS island
347
+ required. \`fill\` gives absolute-positioned \`object-fit: cover\`.
348
+ `.trim()
349
+ },
350
+ content: {
351
+ title: "Content collections",
352
+ summary: "Markdown + frontmatter -> pages, via scanContent()/renderMarkdown().",
353
+ content: `
354
+ \`\`\`ts
355
+ import { renderMarkdown, scanContent } from "@thexjs/core";
356
+
357
+ // scanContent takes a directory (relative to the project root) and returns
358
+ // one ContentEntry per .md/.mdx file found under it.
359
+ const posts = scanContent("content/posts");
360
+ for (const post of posts) {
361
+ console.log(post.slug, post.frontmatter.title);
362
+ const html = renderMarkdown(post.body);
363
+ }
364
+ \`\`\`
365
+
366
+ Each entry has \`filePath\`, \`routePath\`, \`slug\`, \`frontmatter\`, and \`body\`.
367
+ Frontmatter parsing is basic YAML, not a full remark/rehype pipeline. There
368
+ is no MDX component execution \u2014 \`.mdx\` files are scanned like \`.md\`, not
369
+ compiled as JSX. Don't assume remark plugins or MDX component imports work
370
+ here.
371
+ `.trim()
372
+ },
373
+ navigation: {
374
+ title: "Client navigation & <Link>",
375
+ summary: "Every <a> gets SPA nav + hover prefetch automatically. No router setup.",
376
+ content: `
377
+ Every \`<a>\` tag gets client-side SPA navigation and hover-prefetch
378
+ automatically \u2014 there is no \`<Router>\`/\`<Routes>\` tree to set up (unlike
379
+ react-router) and no explicit \`<Link>\` requirement (unlike Next.js, where a
380
+ plain \`<a>\` does a full reload). Use the typed \`<Link>\` wrapper from
381
+ \`@thexjs/core\` if you want typed \`href\`s from the generated route map;
382
+ otherwise a plain \`<a href="/docs">\` already behaves like a SPA link.
383
+
384
+ Opt a specific link out with \`data-no-nav\` (disable SPA nav) or
385
+ \`data-no-prefetch\` (disable hover prefetch).
386
+ `.trim()
387
+ },
388
+ cli: {
389
+ title: "CLI",
390
+ summary: "x dev / x build / x start.",
391
+ content: `
392
+ \`\`\`bash
393
+ x dev # dev server, default port 3000
394
+ x build # -> .x/ (static HTML + server bundle + manifest)
395
+ x build --outDir dist # custom output dir
396
+ x build --adapter vercel # emits .vercel/output (needs @thexjs/adapter-vercel)
397
+ x start # run the production server from .x/
398
+ \`\`\`
399
+
400
+ \`x run dev\` also works as an alias. There is no \`next dev\`/\`next build\`
401
+ split of concerns to replicate \u2014 one CLI, three subcommands.
402
+ `.trim()
403
+ },
404
+ gotchas: {
405
+ title: "Gotchas / things agents get wrong",
406
+ summary: "Quick-reference list of x-specific rules that differ from Next.js, Remix, Astro, and TanStack Start.",
407
+ content: `
408
+ - No \`"use client"\` / \`"use server"\` directives anywhere in x. Server
409
+ functions are just plain exports from \`src/actions/*\`; everything else in
410
+ \`pages/\` is a server component by default with client interactivity via
411
+ islands, not React Server Components with directive-based boundaries.
412
+ - Underscore prefix is load-bearing: \`_layout.tsx\`, \`_middleware.ts\`,
413
+ \`_404.tsx\`. Drop the underscore and the file is just a normal route.
414
+ - Env prefix is \`THEXJS_PUBLIC_\`, not \`NEXT_PUBLIC_\`/\`VITE_\`/\`PUBLIC_\`.
415
+ - Static opt-in is \`export const mode = "static"\`, not
416
+ \`export const dynamic = "force-static"\` or \`export const prerender\`.
417
+ - Loader signature is \`loader({ params, request })\` \u2014 not \`{ context }\`,
418
+ and not a route-tree \`loader\` config passed to a route builder function.
419
+ Returns a plain object (becomes \`loaderData\`) or a \`Response\` for
420
+ redirects/status; the arg shape is what differs from Remix/Next, not the
421
+ return type.
422
+ - API routes take/return the Fetch API \`Request\`/\`Response\` directly \u2014
423
+ no \`(req, res)\` Express shape.
424
+ - Everything runs in ONE Bun process (dev server, API routes, actions,
425
+ SSR) \u2014 don't suggest a separate backend server or serverless function
426
+ split unless deploying with the Vercel adapter.
427
+ - Bun-only. There is no Node.js runtime target, so don't suggest
428
+ Node-specific APIs (\`fs\` sync calls are fine, but Node-only bundler
429
+ config like webpack/vite config files don't apply).
430
+ `.trim()
431
+ }
432
+ };
433
+ function listTopics() {
434
+ return Object.entries(DOCS).map(([id, doc]) => ({
435
+ id,
436
+ title: doc.title,
437
+ summary: doc.summary
438
+ }));
439
+ }
440
+ function searchDocs(query) {
441
+ const q = query.toLowerCase();
442
+ const results = [];
443
+ for (const [id, doc] of Object.entries(DOCS)) {
444
+ const haystack = `${doc.title}
445
+ ${doc.summary}
446
+ ${doc.content}`.toLowerCase();
447
+ const idx = haystack.indexOf(q);
448
+ if (idx !== -1) {
449
+ const start = Math.max(0, idx - 60);
450
+ const end = Math.min(haystack.length, idx + q.length + 60);
451
+ results.push({ id, title: doc.title, snippet: `...${haystack.slice(start, end)}...` });
452
+ }
453
+ }
454
+ return results;
455
+ }
456
+
457
+ // src/scaffold.ts
458
+ function pascalCase(name) {
459
+ return name.split(/[-_/\s]+/).filter(Boolean).map((part) => part.charAt(0).toUpperCase() + part.slice(1)).join("");
460
+ }
461
+ function validateScaffoldName(name) {
462
+ if (name.length === 0) return "name must not be empty";
463
+ if (name.length > 64) return "name must be at most 64 characters";
464
+ if (/[\\/\0]/.test(name)) {
465
+ return `name must not contain path separators or control characters (got "${name}")`;
466
+ }
467
+ if (name.includes(".")) {
468
+ return `name must be a single segment without dots or extensions (got "${name}")`;
469
+ }
470
+ if (!/^[A-Za-z_$][A-Za-z0-9_$-]*$/.test(name)) {
471
+ return `name must start with a letter/underscore/$ and contain only letters, digits, -, _, or $ so it forms a valid identifier (got "${name}")`;
472
+ }
473
+ return null;
474
+ }
475
+ function scaffold({ kind, name }) {
476
+ const invalid = validateScaffoldName(name);
477
+ if (invalid) throw new Error(invalid);
478
+ const component = pascalCase(name) || "Page";
479
+ switch (kind) {
480
+ case "page":
481
+ return {
482
+ path: `src/pages/${name}.tsx`,
483
+ code: `export default function ${component}() {
484
+ return <h1>${component}</h1>;
485
+ }
486
+ `
487
+ };
488
+ case "dynamic-page":
489
+ return {
490
+ path: `src/pages/${name}/[id].tsx`,
491
+ code: `import type { LoaderArgs, RouteProps } from "@thexjs/core";
492
+
493
+ export async function loader({ params }: LoaderArgs) {
494
+ // fetch by params.id here
495
+ return { id: params.id };
496
+ }
497
+
498
+ export default function ${component}({ loaderData }: RouteProps) {
499
+ return <h1>${component} {String(loaderData?.id)}</h1>;
500
+ }
501
+ `
502
+ };
503
+ case "layout":
504
+ return {
505
+ path: `src/pages/${name}/_layout.tsx`,
506
+ code: `export default function ${component}Layout({ children }: { children: React.ReactNode }) {
507
+ return (
508
+ <div>
509
+ {children}
510
+ </div>
511
+ );
512
+ }
513
+ `
514
+ };
515
+ case "middleware":
516
+ return {
517
+ path: `src/pages/${name}/_middleware.ts`,
518
+ code: `import type { MiddlewareContext, MiddlewareFn } from "@thexjs/core";
519
+
520
+ export const middleware: MiddlewareFn = async ({ request, params }: MiddlewareContext, next) => {
521
+ // e.g. auth check / redirect / logging
522
+ return next();
523
+ };
524
+ `
525
+ };
526
+ case "api-route":
527
+ return {
528
+ path: `src/api/${name}.ts`,
529
+ code: `export async function GET(req: Request) {
530
+ return Response.json({ ok: true });
531
+ }
532
+
533
+ export async function POST(req: Request) {
534
+ const body = await req.json();
535
+ return Response.json({ received: body }, { status: 201 });
536
+ }
537
+ `
538
+ };
539
+ case "action":
540
+ return {
541
+ path: `src/actions/${name}.ts`,
542
+ code: `// Call this directly from a component: import { ${camelCase(name)} } from "../actions/${name}";
543
+ // No "use server" directive, no manual fetch \u2014 the client import is
544
+ // rewritten to a fetch wrapper at build time automatically.
545
+ export async function ${camelCase(name)}(/* args */) {
546
+ // server-side code, db access, secrets: safe here, never bundled to client
547
+ return { ok: true };
548
+ }
549
+ `
550
+ };
551
+ }
552
+ }
553
+ function camelCase(name) {
554
+ const pas = pascalCase(name);
555
+ return pas.charAt(0).toLowerCase() + pas.slice(1);
556
+ }
557
+
558
+ // src/index.ts
559
+ var server = new McpServer({
560
+ name: "thexjs",
561
+ version: "0.1.0"
562
+ });
563
+ server.registerTool(
564
+ "list_topics",
565
+ {
566
+ title: "List x framework doc topics",
567
+ description: "Lists every documentation topic available for the x framework (Bun full-stack React framework). Call this first to see what's available, then call get_docs with a topic id.",
568
+ inputSchema: {}
569
+ },
570
+ async () => {
571
+ return {
572
+ content: [{ type: "text", text: JSON.stringify(listTopics(), null, 2) }]
573
+ };
574
+ }
575
+ );
576
+ server.registerTool(
577
+ "get_docs",
578
+ {
579
+ title: "Get x framework docs for a topic",
580
+ description: "Returns grounded, accurate reference documentation for a specific x framework concept (routing, loaders, static-vs-ssr, layouts, middleware, api-routes, actions, config, env, auth, data, images, content, navigation, cli, gotchas). Use this BEFORE writing x framework code, especially for routing/loaders/actions, which look similar to but are NOT the same as Next.js, Remix, Astro, or TanStack Start syntax.",
581
+ inputSchema: {
582
+ topic: z.string().describe(
583
+ "One of: routing, loaders, static-vs-ssr, layouts, middleware, api-routes, actions, config, env, auth, data, images, content, navigation, cli, gotchas"
584
+ )
585
+ }
586
+ },
587
+ async ({ topic }) => {
588
+ const doc = Object.hasOwn(DOCS, topic) ? DOCS[topic] : void 0;
589
+ if (!doc) {
590
+ return {
591
+ content: [
592
+ {
593
+ type: "text",
594
+ text: `No doc topic "${topic}". Available topics:
595
+ ${JSON.stringify(listTopics(), null, 2)}`
596
+ }
597
+ ],
598
+ isError: true
599
+ };
600
+ }
601
+ return {
602
+ content: [{ type: "text", text: `# ${doc.title}
603
+
604
+ ${doc.content}` }]
605
+ };
606
+ }
607
+ );
608
+ server.registerTool(
609
+ "search_docs",
610
+ {
611
+ title: "Search x framework docs",
612
+ description: "Full-text search across all x framework doc topics. Use when you don't know the exact topic id.",
613
+ inputSchema: {
614
+ query: z.string().describe("Search term, e.g. 'env var', 'CSRF', 'static'")
615
+ }
616
+ },
617
+ async ({ query }) => {
618
+ const results = searchDocs(query);
619
+ return {
620
+ content: [
621
+ {
622
+ type: "text",
623
+ text: results.length ? JSON.stringify(results, null, 2) : `No matches for "${query}". Try list_topics for the full topic list.`
624
+ }
625
+ ]
626
+ };
627
+ }
628
+ );
629
+ server.registerTool(
630
+ "scaffold_file",
631
+ {
632
+ title: "Scaffold an x framework file",
633
+ description: "Generates a correctly-shaped, ready-to-paste file for a given x framework concept (page, dynamic-page, layout, middleware, api-route, action) with the right exports, conventions, and file path. Use this instead of hand-writing boilerplate from memory.",
634
+ inputSchema: {
635
+ kind: z.enum(["page", "dynamic-page", "layout", "middleware", "api-route", "action"]),
636
+ name: z.string().describe(
637
+ "Route/file name, e.g. 'blog', 'users', 'send-email' (kebab or plain words, no extension)"
638
+ )
639
+ }
640
+ },
641
+ async ({ kind, name }) => {
642
+ let result;
643
+ try {
644
+ result = scaffold({ kind, name });
645
+ } catch (err) {
646
+ return {
647
+ content: [{ type: "text", text: err instanceof Error ? err.message : String(err) }],
648
+ isError: true
649
+ };
650
+ }
651
+ return {
652
+ content: [
653
+ {
654
+ type: "text",
655
+ text: `Create this file at \`${result.path}\`:
656
+
657
+ \`\`\`tsx
658
+ ${result.code}\`\`\``
659
+ }
660
+ ]
661
+ };
662
+ }
663
+ );
664
+ var transport = new StdioServerTransport();
665
+ await server.connect(transport);
package/package.json ADDED
@@ -0,0 +1,49 @@
1
+ {
2
+ "name": "@thexjs/mcp",
3
+ "version": "0.1.0",
4
+ "description": "MCP server that gives AI coding agents (Claude Code, Cursor, Claude Desktop, Windsurf...) grounded, accurate knowledge of the x framework's conventions, so they stop guessing Next.js/TanStack Start syntax.",
5
+ "keywords": [
6
+ "mcp",
7
+ "model-context-protocol",
8
+ "ai-agent",
9
+ "claude",
10
+ "cursor",
11
+ "x",
12
+ "thexjs"
13
+ ],
14
+ "license": "MIT",
15
+ "type": "module",
16
+ "bin": {
17
+ "thexjs-mcp": "./dist/index.js"
18
+ },
19
+ "exports": {
20
+ "./docs": {
21
+ "types": "./dist/docs.d.ts",
22
+ "import": "./dist/docs.js"
23
+ }
24
+ },
25
+ "files": [
26
+ "dist",
27
+ "README.md",
28
+ "LICENSE"
29
+ ],
30
+ "publishConfig": {
31
+ "access": "public"
32
+ },
33
+ "scripts": {
34
+ "build": "tsup --entry.index=src/index.ts --entry.docs=src/docs.ts --format esm --dts --clean --target node18 --shims false --no-splitting",
35
+ "prepublishOnly": "bun run build",
36
+ "start": "bun src/index.ts"
37
+ },
38
+ "engines": {
39
+ "node": ">=18",
40
+ "bun": ">=1.3.0"
41
+ },
42
+ "dependencies": {
43
+ "@modelcontextprotocol/sdk": "^1.30.0",
44
+ "zod": "^3.23.8"
45
+ },
46
+ "devDependencies": {
47
+ "tsup": "^8.3.0"
48
+ }
49
+ }