@typesol/cli 0.40.0 → 0.41.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/CHANGELOG.md CHANGED
@@ -6,6 +6,34 @@ codes, and says so here.
6
6
 
7
7
  ## Unreleased
8
8
 
9
+ ## 0.41.0 — 2026-11-07
10
+
11
+ TypeSOL for AI coding agents, and Raydium CP-Swap ported in full. `typesol init` writes the rules an agent needs
12
+ (AGENTS.md, CLAUDE.md, Cursor's rules) and an MCP server configuration; `typesol mcp` gives agents check, IDL and docs
13
+ search as tools; `llms.txt` / `llms-full.txt` put the docs in one file for models. Raydium CP-Swap now has all 21 of its
14
+ instructions, checked against today's mainnet binary with a fuzz test. Programs that do not log a narrowed Option
15
+ compile to the same C as in 0.40.0.
16
+
17
+ - AI agents (docs/ai.md): `typesol init` writes AGENTS.md, CLAUDE.md and Cursor's rules (what TypeSOL refuses that
18
+ TypeScript habits produce, how to check and test) and the MCP server's configuration (.mcp.json, .cursor/mcp.json).
19
+ - New: `typesol mcp`, a Model Context Protocol server on stdio with the tools `check` (diagnostics with hints, from a
20
+ file or source text), `idl`, `docs` (search) and `rules`. No new dependencies.
21
+ - New: `llms.txt` and `llms-full.txt` (the rules, the quick start and the reference in one file), built from the docs by
22
+ `scripts/llms.ts`, shipped in the npm package; the tests fail when they are out of date.
23
+ - CLI: `typesol check --json` gives each error's hint as a `hint` field (it stays the message's last line too).
24
+ - Fixed: `log(x)` of an Option that TypeScript narrowed to its value (after `x === null` was ruled out) generated C that
25
+ did not compile; it logs the value now, and a possibly-null Option is refused with what to do instead.
26
+ - Examples: showcase/mainnet/raydium-cp-swap ports all 21 of Raydium CP-Swap's instructions (was 10): `initialize_v2`,
27
+ `initialize_with_permission`, `collect_creator_fee`, `collect_creator_fee_permissionless`, the permission, creator
28
+ fee share and supported-mint accounts (create and close), and `collect_excess_lamports`. Checked against the binary
29
+ on mainnet today (deployed 2026-10-31; test/programs/raydium_cp_swap.so updated): 136 transactions (was 70) with
30
+ the same outcomes, account bytes and events, Raydium's five signing keys replaced by test keys in both so the admin
31
+ instructions run too, and a fuzz test (random swaps, deposits, withdrawals and fee collections in an SPL Token
32
+ and a Token-2022 pool); an exact-output swap for the whole vault now panics as the original does instead of failing
33
+ with 5100. 42–85% fewer compute units; 214,944 bytes against 749,848. docs/case-study-raydium-cp-swap.md.
34
+ - Docs: docs/stability.md, what 1.0 will promise, what is stable already and what is still experimental, and what to
35
+ settle first; the audit package's line counts and its list of unreviewed changes brought up to 0.40.0.
36
+
9
37
  ## 0.40.0 — 2026-11-06
10
38
 
11
39
  Raydium AMM v4 ported in full, a native (non-Anchor) program, and checked against its mainnet binary down to its log
package/README.md CHANGED
@@ -188,6 +188,7 @@ If the build refuses something, the error points at the line and, for the usual
188
188
  case study each (Marginfi v2 in full: all 124 instructions, the same on 2,081 transactions; Raydium AMM v4, a native
189
189
  program, down to its log lines).
190
190
  - To mainnet (wallet, cost, deploy, IDL, verification): [docs/mainnet.md](docs/mainnet.md).
191
+ - With an AI coding agent: [docs/ai.md](docs/ai.md) (agent rules, [llms.txt](https://typesol.com/llms.txt), the MCP server).
191
192
 
192
193
  ## How it works
193
194
 
@@ -227,11 +228,12 @@ The full reference, with every type, check and built-in, is in [docs/language.md
227
228
 
228
229
  | Command | What it does |
229
230
  | --- | --- |
230
- | `typesol init` | scaffold a project with a program, a LiteSVM test and TypeScript configs |
231
+ | `typesol init` | scaffold a project with a program, a LiteSVM test, TypeScript configs and the files AI coding agents read (AGENTS.md, CLAUDE.md, Cursor rules, MCP config) |
231
232
  | `typesol new <program>` | add another program and its test to a project |
232
233
  | `typesol clone <address…>` | copy mainnet accounts and programs for the tests, loaded by `testProgram` |
233
234
  | `typesol build` | compile every program in `typesol.json`, or a single `.ts` file |
234
- | `typesol check` | typecheck and subset-check without compiling (every program of the project, or one file) |
235
+ | `typesol check` | typecheck and subset-check without compiling (every program of the project, or one file); `--json` gives each error's hint as a field |
236
+ | `typesol mcp` | an MCP server for AI coding agents: check, IDL, docs search and the rules as tools ([docs/ai.md](docs/ai.md)) |
235
237
  | `typesol deploy` | `solana program deploy` with the right program keypair (`--dry-run` prints the commands) |
236
238
  | `typesol idl publish` | upload the IDL to the Program Metadata program (canonical when the upgrade authority signs) |
237
239
  | `typesol cpi <idl.json>` | generate typed CPI helpers for another program |
@@ -348,7 +350,7 @@ Case studies: [Marginfi v2](docs/case-study-marginfi.md), [Raydium AMM v4](docs/
348
350
 
349
351
  | | |
350
352
  | --- | --- |
351
- | [`raydium-cp-swap/`](showcase/mainnet/raydium-cp-swap) | Raydium CP-Swap's trading core: constant-product swaps, LP deposits and withdrawals, Token-2022 transfer fees, a price oracle |
353
+ | [`raydium-cp-swap/`](showcase/mainnet/raydium-cp-swap) | Raydium CP-Swap in full, all 21 instructions: constant-product swaps, LP deposits and withdrawals, Token-2022 transfer fees, a price oracle, creator fees and their shares, permissioned pools, supported mints |
352
354
  | [`raydium-clmm/`](showcase/mainnet/raydium-clmm) | Raydium CLMM in full: concentrated-liquidity positions as NFTs, swaps and multi-hop routes across tick arrays, limit orders, rewards, dynamic fees, u256 math |
353
355
  | [`jito-mev/`](showcase/mainnet/jito-mev) | Jito's tip payment, tip distribution and priority fee distribution: tips paid out per leader, Merkle-proof claims, epochs and expiry |
354
356
  | [`marginfi/`](showcase/mainnet/marginfi) | Marginfi v2 in full, all 124 instructions: I80F48 fixed-point arithmetic, zero-copy accounts, oracles (Pyth, Switchboard, staked SOL, Scope, venue exchange rates), the risk engine, liquidation and bankruptcy, flash loans, orders, rebalances, and the Solend, Kamino, Drift and JupLend banks |
@@ -368,7 +370,8 @@ change.
368
370
  external audit.
369
371
  - Report vulnerabilities as described in [SECURITY.md](SECURITY.md).
370
372
 
371
- Not supported yet: see the end of [docs/language.md](docs/language.md#not-supported-yet).
373
+ Not supported yet: see the end of [docs/language.md](docs/language.md#not-supported-yet). What 1.0 will promise, what is
374
+ stable already and what is still experimental: [docs/stability.md](docs/stability.md).
372
375
 
373
376
  ## Requirements
374
377
 
package/dist/ai.d.ts ADDED
@@ -0,0 +1,10 @@
1
+ /** The rules every TypeSOL program follows that a model trained on ordinary TypeScript gets wrong first. */
2
+ export declare const AGENT_RULES = "## Writing TypeSOL\n\nTypeSOL compiles a subset of TypeScript to a Solana program (native SBF) with an Anchor-compatible IDL. Programs live\nin `programs/`, tests in `tests/`; `typesol.json` lists the programs.\n\n- Exported functions are instructions; their parameters are the accounts (`Signer`, `Account<T>`, `Mut<T>`,\n `Init<T>`, token accounts, programs) and then the arguments. Account data types are exported interfaces.\n- Integers are bigint: `u8` \u2026 `u128`, `i8` \u2026 `i128` (write `1n`, never `1`; take `u64`, never `number`).\n Arithmetic is checked: an overflow fails the instruction. There is no floating point.\n- Import everything from `\"typesol\"`: types, and functions such as `require`, `log`, `min`, `max`,\n `fixedArray`, `emit`, `invoke`.\n- Fail with `require(condition, MyError.Name)` (an exported string enum of messages) or `require(condition, \"message\")`.\n There is no `throw`, `try`, `async`, `class`, `console` or `Math`.\n- An account the instruction changes is `Mut<T>`; one it creates is `Init<T>` (`acct.create(payer, seeds)`).\n- Lists: `FixedArray<T, N>`, `FixedVec<T, N>`, `Vec<T>`; read with `.get(i)` and write with `.set(i, v)`\n (`i` a bigint), not `xs[i]`. `map`, `filter`, `find`, `some`, `reduce` work on them.\n- Strings are `FixedString<N>` in account data; `Option<T>` (`T | null`) for optional values.\n\n## Checking your work\n\n- `npx typesol check` (or `--json`) type-checks every program and lists what TypeSOL refuses, each error with a\n `hint` that says what to write instead. Fix those first; they are faster than a build.\n- `npm test` builds the programs and runs `tests/` in LiteSVM (an in-process Solana runtime). `npx typesol build`\n writes `target/<name>/`: the `.so`, the IDL and a typed client.\n- The MCP server (`npx typesol mcp`, configured in `.mcp.json` and `.cursor/mcp.json`) gives the same check,\n the IDL and the docs as tools.\n- The language reference: `node_modules/typesol/docs/language.md`, or https://typesol.com/llms-full.txt.\n";
3
+ /** AGENTS.md for a new project (Codex, Cursor, Zed, and other agents that read it). */
4
+ export declare function agentsMd(name: string): string;
5
+ /** Claude Code reads CLAUDE.md, which imports AGENTS.md so the rules are kept in one place. */
6
+ export declare const CLAUDE_MD = "@AGENTS.md\n";
7
+ /** Cursor's project rules, always applied to the program and test files. */
8
+ export declare function cursorRule(): string;
9
+ /** The MCP server configuration Claude Code (.mcp.json) and Cursor (.cursor/mcp.json) read. */
10
+ export declare const MCP_JSON: string;
package/dist/ai.js ADDED
@@ -0,0 +1,43 @@
1
+ // What an AI coding agent needs to write TypeSOL: the rules `typesol init` puts in AGENTS.md (and CLAUDE.md, Cursor's
2
+ // rules), the MCP server configurations it writes, and the llms.txt files built from the docs (scripts/llms.ts).
3
+ /** The rules every TypeSOL program follows that a model trained on ordinary TypeScript gets wrong first. */
4
+ export const AGENT_RULES = `## Writing TypeSOL
5
+
6
+ TypeSOL compiles a subset of TypeScript to a Solana program (native SBF) with an Anchor-compatible IDL. Programs live
7
+ in \`programs/\`, tests in \`tests/\`; \`typesol.json\` lists the programs.
8
+
9
+ - Exported functions are instructions; their parameters are the accounts (\`Signer\`, \`Account<T>\`, \`Mut<T>\`,
10
+ \`Init<T>\`, token accounts, programs) and then the arguments. Account data types are exported interfaces.
11
+ - Integers are bigint: \`u8\` … \`u128\`, \`i8\` … \`i128\` (write \`1n\`, never \`1\`; take \`u64\`, never \`number\`).
12
+ Arithmetic is checked: an overflow fails the instruction. There is no floating point.
13
+ - Import everything from \`"typesol"\`: types, and functions such as \`require\`, \`log\`, \`min\`, \`max\`,
14
+ \`fixedArray\`, \`emit\`, \`invoke\`.
15
+ - Fail with \`require(condition, MyError.Name)\` (an exported string enum of messages) or \`require(condition, "message")\`.
16
+ There is no \`throw\`, \`try\`, \`async\`, \`class\`, \`console\` or \`Math\`.
17
+ - An account the instruction changes is \`Mut<T>\`; one it creates is \`Init<T>\` (\`acct.create(payer, seeds)\`).
18
+ - Lists: \`FixedArray<T, N>\`, \`FixedVec<T, N>\`, \`Vec<T>\`; read with \`.get(i)\` and write with \`.set(i, v)\`
19
+ (\`i\` a bigint), not \`xs[i]\`. \`map\`, \`filter\`, \`find\`, \`some\`, \`reduce\` work on them.
20
+ - Strings are \`FixedString<N>\` in account data; \`Option<T>\` (\`T | null\`) for optional values.
21
+
22
+ ## Checking your work
23
+
24
+ - \`npx typesol check\` (or \`--json\`) type-checks every program and lists what TypeSOL refuses, each error with a
25
+ \`hint\` that says what to write instead. Fix those first; they are faster than a build.
26
+ - \`npm test\` builds the programs and runs \`tests/\` in LiteSVM (an in-process Solana runtime). \`npx typesol build\`
27
+ writes \`target/<name>/\`: the \`.so\`, the IDL and a typed client.
28
+ - The MCP server (\`npx typesol mcp\`, configured in \`.mcp.json\` and \`.cursor/mcp.json\`) gives the same check,
29
+ the IDL and the docs as tools.
30
+ - The language reference: \`node_modules/typesol/docs/language.md\`, or https://typesol.com/llms-full.txt.
31
+ `;
32
+ /** AGENTS.md for a new project (Codex, Cursor, Zed, and other agents that read it). */
33
+ export function agentsMd(name) {
34
+ return `# ${name}\n\nA Solana program written in TypeSOL (https://typesol.com).\n\n${AGENT_RULES}`;
35
+ }
36
+ /** Claude Code reads CLAUDE.md, which imports AGENTS.md so the rules are kept in one place. */
37
+ export const CLAUDE_MD = "@AGENTS.md\n";
38
+ /** Cursor's project rules, always applied to the program and test files. */
39
+ export function cursorRule() {
40
+ return `---\ndescription: TypeSOL, a TypeScript subset compiled to Solana programs\nglobs: programs/**/*.ts, tests/**/*.ts\nalwaysApply: true\n---\n\n${AGENT_RULES}`;
41
+ }
42
+ /** The MCP server configuration Claude Code (.mcp.json) and Cursor (.cursor/mcp.json) read. */
43
+ export const MCP_JSON = JSON.stringify({ mcpServers: { typesol: { command: "npx", args: ["typesol", "mcp"] } } }, null, 2) + "\n";
package/dist/cli.js CHANGED
@@ -66,7 +66,7 @@ const COMMANDS = {
66
66
  init: {
67
67
  usage: "typesol init [<dir>] [--name <program>] [--template counter|vault|escrow]",
68
68
  help: [
69
- "Create a project: typesol.json, programs/<name>.ts, tests/<name>.test.ts (LiteSVM), package.json, tsconfig.json, .gitignore, .vscode/settings.json (editor errors).",
69
+ "Create a project: typesol.json, programs/<name>.ts, tests/<name>.test.ts (LiteSVM), package.json, tsconfig.json, .gitignore, .vscode/settings.json (editor errors), AGENTS.md / CLAUDE.md / .cursor/rules (the rules for AI coding agents) and .mcp.json / .cursor/mcp.json (the TypeSOL MCP server).",
70
70
  "Refuses to overwrite files. <name> must be snake_case (default: derived from <dir>).",
71
71
  "--template counter a PDA counter per user (default)",
72
72
  "--template vault a SOL vault at a PDA: deposit, withdraw above rent, close",
@@ -225,6 +225,20 @@ const COMMANDS = {
225
225
  return 0;
226
226
  },
227
227
  },
228
+ mcp: {
229
+ usage: "typesol mcp",
230
+ help: [
231
+ "Serve the Model Context Protocol on stdio for AI coding agents: tools to check a program (errors with hints), read",
232
+ "its IDL, search the docs, and read the rules a TypeSOL program follows. `typesol init` writes .mcp.json (Claude",
233
+ "Code) and .cursor/mcp.json (Cursor) that start it as `npx typesol mcp`.",
234
+ ].join("\n "),
235
+ options: {},
236
+ async run() {
237
+ const { serve } = await import("./tools/mcp.js");
238
+ await serve();
239
+ return 0;
240
+ },
241
+ },
228
242
  doctor: {
229
243
  usage: "typesol doctor [--url <rpc>] [--config <solana cli config>]",
230
244
  help: [
@@ -263,10 +263,11 @@ function typecheck(entry, files) {
263
263
  const flat = ts.flattenDiagnosticMessageText(d.messageText, "\n");
264
264
  const hint = hintForTypeScript(d, flat, LIB_PATH);
265
265
  const message = hint ? `${flat}\nhint: ${hint}` : flat;
266
+ const extra = hint ? { hint } : {};
266
267
  if (!d.file || d.start === undefined)
267
- return { file: entry, line: 1, column: 1, message };
268
+ return { file: entry, line: 1, column: 1, message, ...extra };
268
269
  const { line, character } = d.file.getLineAndCharacterOfPosition(d.start);
269
- return { file: d.file.fileName, line: line + 1, column: character + 1, message, length: d.length };
270
+ return { file: d.file.fileName, line: line + 1, column: character + 1, message, length: d.length, ...extra };
270
271
  });
271
272
  throw new CompileError(diagnostics);
272
273
  }
@@ -6,6 +6,8 @@ export interface Diagnostic {
6
6
  message: string;
7
7
  /** Characters the problem spans from line:column (the construct refused), when known. */
8
8
  length?: number;
9
+ /** What to write instead, when known (also the message's last line, "hint: …"): for tools and AI agents. */
10
+ hint?: string;
9
11
  }
10
12
  export declare class CompileError extends Error {
11
13
  readonly diagnostics: Diagnostic[];
@@ -121,7 +121,14 @@ export class CallEmitter extends ExpressionEmitter {
121
121
  this.line(`sol_log_((const char *)${t}.ptr, ${t}.len);`);
122
122
  }
123
123
  else {
124
- const value = v.literal !== undefined ? this.expect(v, U64, args[0]) : v;
124
+ let value = v.literal !== undefined ? this.expect(v, U64, args[0]) : v;
125
+ // An Option TypeScript has narrowed to its value (after `x === null` was ruled out): log the value.
126
+ if (value.type.kind === "option") {
127
+ const t = this.checker.getTypeAtLocation(args[0]);
128
+ if (t.isUnion() && t.types.some((m) => m.flags & (ts.TypeFlags.Null | ts.TypeFlags.Undefined)))
129
+ this.fail(args[0], "log() takes a value, not an Option that may be null: check `x !== null` first, or log `${x}` (null prints as null)");
130
+ value = this.unwrap(value, args[0]);
131
+ }
125
132
  if (value.type.kind === "pubkey")
126
133
  this.line(`sol_log_pubkey(${value.c});`);
127
134
  else if (value.type.kind === "int") {
@@ -0,0 +1,11 @@
1
+ type Message = {
2
+ jsonrpc: "2.0";
3
+ id?: number | string | null;
4
+ method?: string;
5
+ params?: Record<string, unknown>;
6
+ };
7
+ /** One request's response (undefined for a notification). */
8
+ export declare function handle(msg: Message): object | undefined;
9
+ /** Serve on stdin / stdout until stdin closes. Logs go to stderr: stdout carries only protocol messages. */
10
+ export declare function serve(): Promise<void>;
11
+ export {};
@@ -0,0 +1,208 @@
1
+ // `typesol mcp`: a Model Context Protocol server over stdio (newline-delimited JSON-RPC 2.0), so an AI coding agent
2
+ // (Claude Code, Cursor, …) can check a program, read its IDL and search the TypeSOL docs as tools. No dependencies.
3
+ import { existsSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs";
4
+ import os from "node:os";
5
+ import path from "node:path";
6
+ import { fileURLToPath } from "node:url";
7
+ import { AGENT_RULES } from "../ai.js";
8
+ import { CompileError, COMPILER_VERSION, generate } from "../compiler/index.js";
9
+ import { buildIdl } from "../compiler/idl.js";
10
+ const DOCS = fileURLToPath(new URL("../../docs", import.meta.url));
11
+ const README = fileURLToPath(new URL("../../README.md", import.meta.url));
12
+ /** Any address: the IDL's `address` field, when the caller gives none. */
13
+ const PLACEHOLDER_ADDRESS = "11111111111111111111111111111111";
14
+ /** The program to work on: a file path, or source text (written to a temporary file, so imports of "typesol" work). */
15
+ function withProgram(args, fn) {
16
+ if (typeof args.file === "string") {
17
+ const file = path.resolve(args.file);
18
+ if (!existsSync(file))
19
+ throw new Error(`no such file: ${file}`);
20
+ return fn(file);
21
+ }
22
+ if (typeof args.source !== "string")
23
+ throw new Error("give `file` (a path) or `source` (the program's text)");
24
+ const dir = mkdtempSync(path.join(os.tmpdir(), "typesol-mcp-"));
25
+ const entry = path.join(dir, "program.ts");
26
+ writeFileSync(entry, args.source);
27
+ try {
28
+ return fn(entry, new Map([[entry, args.source]]));
29
+ }
30
+ finally {
31
+ rmSync(dir, { recursive: true, force: true });
32
+ }
33
+ }
34
+ /** The docs as sections (a heading and what follows it), for the search tool. */
35
+ function sections() {
36
+ const out = [];
37
+ const files = [
38
+ README,
39
+ ...(existsSync(DOCS)
40
+ ? readdirSync(DOCS)
41
+ .filter((f) => f.endsWith(".md"))
42
+ .map((f) => path.join(DOCS, f))
43
+ : []),
44
+ ];
45
+ for (const f of files) {
46
+ const name = path.basename(f);
47
+ let heading = name;
48
+ let text = [];
49
+ const flush = () => {
50
+ if (text.join("").trim())
51
+ out.push({ source: name, heading, text: text.join("\n").trim() });
52
+ text = [];
53
+ };
54
+ for (const line of readFileSync(f, "utf8").split("\n")) {
55
+ if (/^#{1,3} /.test(line)) {
56
+ flush();
57
+ heading = line.replace(/^#+ /, "");
58
+ }
59
+ else
60
+ text.push(line);
61
+ }
62
+ flush();
63
+ }
64
+ return out;
65
+ }
66
+ const TOOLS = [
67
+ {
68
+ name: "check",
69
+ description: "Type-check a TypeSOL program and list what the compiler refuses, each with its file, line, column, message and, for the usual mistakes, a hint saying what to write instead. Give `file` (a path) or `source` (the program's text).",
70
+ inputSchema: {
71
+ type: "object",
72
+ properties: {
73
+ file: { type: "string", description: "path to the program's entry .ts file" },
74
+ source: { type: "string", description: "the program's source text" },
75
+ },
76
+ },
77
+ run(args) {
78
+ return withProgram(args, (entry, files) => {
79
+ try {
80
+ const { model } = generate(entry, { files });
81
+ return { text: JSON.stringify({ ok: true, program: model.name, instructions: model.instructions.map((i) => i.name), diagnostics: [] }) };
82
+ }
83
+ catch (e) {
84
+ if (!(e instanceof CompileError))
85
+ throw e;
86
+ // Source given as text is reported as program.ts, not the temporary file it was checked in.
87
+ const diagnostics = files ? e.diagnostics.map((d) => ({ ...d, file: path.basename(d.file) })) : e.diagnostics;
88
+ return { text: JSON.stringify({ ok: false, diagnostics }) };
89
+ }
90
+ });
91
+ },
92
+ },
93
+ {
94
+ name: "idl",
95
+ description: "The Anchor-compatible IDL a TypeSOL program compiles to (instructions, accounts, types, errors, events). Give `file` or `source`.",
96
+ inputSchema: {
97
+ type: "object",
98
+ properties: { file: { type: "string" }, source: { type: "string" }, address: { type: "string", description: "the program address to record" } },
99
+ },
100
+ run(args) {
101
+ return withProgram(args, (entry, files) => {
102
+ try {
103
+ const address = typeof args.address === "string" ? args.address : PLACEHOLDER_ADDRESS;
104
+ return { text: JSON.stringify(buildIdl(generate(entry, { files }).model, address), null, 2) };
105
+ }
106
+ catch (e) {
107
+ if (!(e instanceof CompileError))
108
+ throw e;
109
+ return { text: JSON.stringify({ ok: false, diagnostics: e.diagnostics }), isError: true };
110
+ }
111
+ });
112
+ },
113
+ },
114
+ {
115
+ name: "docs",
116
+ description: "Search the TypeSOL documentation (the language reference, errors, testing, CLI, porting from Anchor, case studies). Returns the best-matching sections.",
117
+ inputSchema: { type: "object", properties: { query: { type: "string" }, limit: { type: "number" } }, required: ["query"] },
118
+ run(args) {
119
+ const words = String(args.query ?? "")
120
+ .toLowerCase()
121
+ .split(/\W+/)
122
+ .filter((w) => w.length > 1);
123
+ if (!words.length)
124
+ throw new Error("give a `query`");
125
+ const scored = sections()
126
+ .map((s) => {
127
+ const hay = `${s.heading}\n${s.text}`.toLowerCase();
128
+ const score = words.reduce((n, w) => n + (hay.split(w).length - 1) + (s.heading.toLowerCase().includes(w) ? 5 : 0), 0);
129
+ return { s, score };
130
+ })
131
+ .filter((x) => x.score > 0)
132
+ .sort((a, b) => b.score - a.score)
133
+ .slice(0, Math.max(1, Math.min(10, Number(args.limit ?? 4))));
134
+ if (!scored.length)
135
+ return { text: "No section matches; try other words, or the `rules` tool." };
136
+ return { text: scored.map(({ s }) => `# ${s.heading} (${s.source})\n\n${s.text.slice(0, 4000)}`).join("\n\n---\n\n") };
137
+ },
138
+ },
139
+ {
140
+ name: "rules",
141
+ description: "The rules a TypeSOL program follows that ordinary TypeScript habits break (bigint integers, imports, no throw/async/class, Mut<T> for changed accounts, …), and how to check and test.",
142
+ inputSchema: { type: "object", properties: {} },
143
+ run() {
144
+ return { text: AGENT_RULES };
145
+ },
146
+ },
147
+ ];
148
+ /** One request's response (undefined for a notification). */
149
+ export function handle(msg) {
150
+ const reply = (result) => ({ jsonrpc: "2.0", id: msg.id ?? null, result });
151
+ const fail = (code, message) => ({ jsonrpc: "2.0", id: msg.id ?? null, error: { code, message } });
152
+ if (msg.id === undefined || msg.id === null)
153
+ return undefined; // notifications (notifications/initialized, …)
154
+ switch (msg.method) {
155
+ case "initialize":
156
+ return reply({
157
+ protocolVersion: typeof msg.params?.protocolVersion === "string" ? msg.params.protocolVersion : "2025-06-18",
158
+ capabilities: { tools: {} },
159
+ serverInfo: { name: "typesol", version: COMPILER_VERSION },
160
+ instructions: "TypeSOL compiles a TypeScript subset to Solana programs. Call `rules` first, `check` after every edit, `docs` for the reference.",
161
+ });
162
+ case "ping":
163
+ return reply({});
164
+ case "tools/list":
165
+ return reply({ tools: TOOLS.map(({ name, description, inputSchema }) => ({ name, description, inputSchema })) });
166
+ case "tools/call": {
167
+ const tool = TOOLS.find((t) => t.name === msg.params?.name);
168
+ if (!tool)
169
+ return fail(-32602, `unknown tool: ${String(msg.params?.name)}`);
170
+ try {
171
+ const out = tool.run(msg.params?.arguments ?? {});
172
+ return reply({ content: [{ type: "text", text: out.text }], isError: !!out.isError });
173
+ }
174
+ catch (e) {
175
+ return reply({ content: [{ type: "text", text: e instanceof Error ? e.message : String(e) }], isError: true });
176
+ }
177
+ }
178
+ default:
179
+ return fail(-32601, `method not found: ${String(msg.method)}`);
180
+ }
181
+ }
182
+ /** Serve on stdin / stdout until stdin closes. Logs go to stderr: stdout carries only protocol messages. */
183
+ export function serve() {
184
+ return new Promise((resolve) => {
185
+ let buffer = "";
186
+ process.stdin.setEncoding("utf8");
187
+ process.stdin.on("data", (chunk) => {
188
+ buffer += chunk;
189
+ let nl;
190
+ while ((nl = buffer.indexOf("\n")) >= 0) {
191
+ const line = buffer.slice(0, nl).trim();
192
+ buffer = buffer.slice(nl + 1);
193
+ if (!line)
194
+ continue;
195
+ let out;
196
+ try {
197
+ out = handle(JSON.parse(line));
198
+ }
199
+ catch {
200
+ out = { jsonrpc: "2.0", id: null, error: { code: -32700, message: "parse error" } };
201
+ }
202
+ if (out)
203
+ process.stdout.write(JSON.stringify(out) + "\n");
204
+ }
205
+ });
206
+ process.stdin.on("end", () => resolve());
207
+ });
208
+ }
package/dist/workspace.js CHANGED
@@ -11,6 +11,7 @@
11
11
  * Program keypairs live in `<out>/deploy/<name>-keypair.json` (created on first build; keep them, never commit them).
12
12
  * The address is recorded in typesol.json on first build, so a lost or swapped keypair is caught before deploying.
13
13
  */
14
+ import { agentsMd, CLAUDE_MD, cursorRule, MCP_JSON } from "./ai.js";
14
15
  import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
15
16
  import path from "node:path";
16
17
  import { writeClient } from "./tools/clientgen.js";
@@ -170,6 +171,13 @@ export function scaffold(dir, name, template = "counter") {
170
171
  ...t.devDependencies,
171
172
  },
172
173
  }, null, 2) + "\n",
174
+ // AI coding agents: the rules (AGENTS.md, and CLAUDE.md / Cursor's rules pointing at the same text) and the
175
+ // TypeSOL MCP server (check, IDL, docs as tools).
176
+ "AGENTS.md": agentsMd(name),
177
+ "CLAUDE.md": CLAUDE_MD,
178
+ ".cursor/rules/typesol.mdc": cursorRule(),
179
+ ".mcp.json": MCP_JSON,
180
+ ".cursor/mcp.json": MCP_JSON,
173
181
  // VS Code loads tsconfig plugins (typesol/ts-plugin) only with the workspace's TypeScript: offer to switch to it.
174
182
  ".vscode/settings.json": JSON.stringify({ "typescript.tsdk": "node_modules/typescript/lib", "typescript.enablePromptUseWorkspaceTsdk": true }, null, 2) + "\n",
175
183
  // target/deploy/*-keypair.json are the programs' addresses: never commit them, but keep a backup.
package/docs/ai.md ADDED
@@ -0,0 +1,52 @@
1
+ # Writing TypeSOL with an AI agent
2
+
3
+ TypeSOL is TypeScript, which AI coding agents write well, but a subset of it: a model's ordinary habits (`1` for an
4
+ integer, `console.log`, `throw`, `xs[i]`) are refused. Four things close that gap.
5
+
6
+ ## The rules in the project
7
+
8
+ `typesol init` writes the rules an agent needs into the project:
9
+
10
+ | File | Read by |
11
+ | --- | --- |
12
+ | `AGENTS.md` | Codex, Cursor, Zed, Aider and other agents that read AGENTS.md |
13
+ | `CLAUDE.md` (`@AGENTS.md`) | Claude Code |
14
+ | `.cursor/rules/typesol.mdc` | Cursor (always applied to `programs/` and `tests/`) |
15
+
16
+ They say what ordinary TypeScript habits break (bigint integers, imports from `"typesol"`, no `throw` / `async` /
17
+ `class`, `Mut<T>` for an account that changes, `.get(i)` / `.set(i, v)` on lists) and how to check and test. Keep your
18
+ own project notes below them in AGENTS.md.
19
+
20
+ ## llms.txt
21
+
22
+ [typesol.com/llms.txt](https://typesol.com/llms.txt) is the index of the docs for models
23
+ ([llmstxt.org](https://llmstxt.org)); [llms-full.txt](https://typesol.com/llms-full.txt) is the rules, the quick start
24
+ and the reference (language, errors, tests, CLI, client, porting from Anchor, troubleshooting, mainnet, security model)
25
+ in one file, to paste into a chat or give to a model as context. Both also ship in the npm package
26
+ (`node_modules/typesol/llms-full.txt`).
27
+
28
+ ## Errors an agent can fix by itself
29
+
30
+ `typesol check --json` prints `{ "ok": false, "diagnostics": [...] }`; each diagnostic has `file`, `line`, `column`,
31
+ `length`, `message` and, for the usual mistakes, `hint`: what to write instead ("integers (u64, u32, i64 …) are bigint
32
+ in TypeSOL: write 1n, not 1, and take u64, not number"). An agent can loop on check → edit → check without building.
33
+
34
+ ## The MCP server
35
+
36
+ `typesol mcp` serves the [Model Context Protocol](https://modelcontextprotocol.io) on stdio. `typesol init` writes
37
+ `.mcp.json` (Claude Code) and `.cursor/mcp.json` (Cursor) that start it with `npx typesol mcp`. Other clients take the
38
+ same command:
39
+
40
+ ```json
41
+ { "mcpServers": { "typesol": { "command": "npx", "args": ["typesol", "mcp"] } } }
42
+ ```
43
+
44
+ | Tool | What it does |
45
+ | --- | --- |
46
+ | `check` | type-checks a program (`file`, or `source` text) and returns the diagnostics with their hints |
47
+ | `idl` | the Anchor-compatible IDL the program compiles to |
48
+ | `docs` | searches the docs and returns the best-matching sections |
49
+ | `rules` | the rules above |
50
+
51
+ Building and testing stay in the shell (`npm test`, `npx typesol build`): they need the platform-tools and write
52
+ files, which an agent should do in the open.
package/docs/audit.md CHANGED
@@ -7,21 +7,21 @@ with TypeSOL are out of scope; their authors audit them.
7
7
 
8
8
  ## Scope
9
9
 
10
- In order of priority. Line counts at 0.38.0 plus main (November 2026).
10
+ In order of priority. Line counts at 0.40.0 (November 2026).
11
11
 
12
12
  | Priority | Component | Files | Lines | Why |
13
13
  | --- | --- | --- | ---: | --- |
14
- | 1 | C runtime | `runtime/typesol_rt.h` | 2,407 | In every program: input parsing, account checks, checked arithmetic, PDAs, system and token CPIs, account creation, resizing and closing, oracles, signature checks, the heap |
15
- | 1 | Instruction prologue and constraints | `src/compiler/emit/function.ts` | 733 | Which checks each account parameter gets, and their order |
16
- | 1 | Account data, Vecs and assignment | `src/compiler/emit/alias.ts`, `storage.ts`, `statements.ts`, `base.ts` | 2,577 | Reads and writes of account data, growable Vec layout and resizing, references and aliasing, closure and helper expansion |
17
- | 1 | Calls and CPIs | `src/compiler/emit/calls.ts`, `cpi-core.ts`, `cpi.ts`, `create.ts`, `token.ts` | 3,730 | Built-ins, remaining accounts, `invoke` / `invokeInstruction` and their account flags, signer seeds, token CPIs, account creation |
14
+ | 1 | C runtime | `runtime/typesol_rt.h` | 2,510 | In every program: input parsing, account checks, checked arithmetic, PDAs, system and token CPIs, account creation, resizing and closing, oracles, signature checks, the heap |
15
+ | 1 | Instruction prologue and constraints | `src/compiler/emit/function.ts` | 870 | Which checks each account parameter gets, and their order |
16
+ | 1 | Account data, Vecs and assignment | `src/compiler/emit/alias.ts`, `storage.ts`, `statements.ts`, `base.ts` | 2,802 | Reads and writes of account data, growable Vec layout and resizing, references and aliasing, closure and helper expansion |
17
+ | 1 | Calls and CPIs | `src/compiler/emit/calls.ts`, `cpi-core.ts`, `cpi.ts`, `create.ts`, `token.ts` | 4,084 | Built-ins, remaining accounts, `invoke` / `invokeInstruction` and their account flags, signer seeds, token CPIs, account creation |
18
18
  | 1 | Metaplex CPIs | `src/compiler/emit/metaplex.ts` | 1,454 | Token Metadata, Core and Bubblegum instruction layouts and their account lists |
19
- | 1 | Expressions | `src/compiler/emit/expressions.ts`, `shared.ts`, `borsh.ts` | 1,656 | Checked arithmetic and casts, Borsh encoding of arguments and `@layout borsh` accounts |
20
- | 2 | Front end | `src/compiler/analyze.ts`, `model.ts` | 2,715 | What the language accepts; constraints and account types as parsed from the source |
21
- | 2 | Interface | `src/compiler/idl.ts`, `src/tools/clientgen.ts` | 2,293 | The IDL and the generated client must describe the program exactly (a mismatch can make clients sign the wrong thing) |
19
+ | 1 | Expressions | `src/compiler/emit/expressions.ts`, `shared.ts`, `borsh.ts` | 1,820 | Checked arithmetic and casts, Borsh encoding of arguments and `@layout borsh` accounts |
20
+ | 2 | Front end | `src/compiler/analyze.ts`, `model.ts` | 2,930 | What the language accepts; constraints and account types as parsed from the source |
21
+ | 2 | Interface | `src/compiler/idl.ts`, `src/tools/clientgen.ts` | 2,316 | The IDL and the generated client must describe the program exactly (a mismatch can make clients sign the wrong thing) |
22
22
  | 3 | Build and tooling | `src/compiler/toolchain.ts`, `src/cli.ts`, `src/workspace.ts`, `src/tools/` | | Build flags, deploy and verification commands |
23
23
 
24
- The language surface is `lib/typesol.d.ts` (2,057 lines): every type and built-in a program can use, with its
24
+ The language surface is `lib/typesol.d.ts` (2,163 lines): every type and built-in a program can use, with its
25
25
  documented behavior. [docs/language.md](language.md) is the reference; [docs/architecture.md](architecture.md) maps
26
26
  the code, [docs/runtime.md](runtime.md) the runtime's conventions.
27
27
 
@@ -49,11 +49,13 @@ accepts. Areas where a bug would be most damaging, and where earlier internal re
49
49
  ## Earlier reviews
50
50
 
51
51
  Internal reviews, by the maintainers, in October 2026. Their findings and fixes are in the CHANGELOG. The releases
52
- after 0.25.0 (0.26.0 to 0.38.0, and main since) have had no review of this kind yet; they add, among others, `u256`,
53
- big-endian seeds and accounts loaded in the body (0.37.0), stored bumps in nested fields and error members without
54
- messages (0.38.0), and on main `@code`, `@repr` / `@serialization`, `@bytes` / `@idlName`, `f64`, Options inside
55
- Options in arguments and events, and loop-scoped `loadAccountMut` with `Dup<T>`. An external review should include
56
- them.
52
+ after 0.25.0 (0.26.0 to 0.40.0) have had no review of this kind yet; they add, among others, `u256`, big-endian seeds
53
+ and accounts loaded in the body (0.37.0), stored bumps in nested fields and error members without messages (0.38.0),
54
+ `@code`, `@repr` / `@serialization`, `@bytes` / `@idlName`, `f64`, Options inside Options in arguments and events,
55
+ loop-scoped `loadAccountMut` with `Dup<T>`, account resizing and raw writes, `systemProgram.createPda` (0.39.0), and
56
+ the native-program surface: `loadRaw` / `loadRawMut` (accounts without a discriminator), instruction data readers,
57
+ error code 0, built-in ProgramErrors, `panic`, `PANIC_ON_OVERFLOW` (0.40.0). An external review should include them;
58
+ the native-program surface first, since it skips the account checks Anchor-style parameters get.
57
59
 
58
60
  - **0.25.0** (runtime and emitted checks): two Medium issues fixed, a remaining account loaded mutably twice through
59
61
  the same slot, and a Vec element written after its right side resized the Vec; plus a token program ambiguity,