Angular token saver

io.github.Alex88Ryabov由 GitHub 账号 Alex88Ryabov 发布v0.2.0更新于 Oct 24, 2026

Compiler-backed Angular template answers, component contracts and version facts for AI agents

已验证STDIO仅桌面知识与记忆开发者工具

概览

AI 生成的概览

让 AI 助手借助 Angular 项目自身的编译器和源码,查询模板定义、诊断、组件契约、使用位置和版本差异

可以做什么
定位模板某一行上的符号在哪里声明,并获取单个模板或一批文件的 Angular 编译器错误,结果来自项目的语言服务器。读取组件或指令的公开契约,包括通过基类继承的成员。列出工作区各项目及其 Angular 版本、strictTemplates 和 zone.js 设置。查询项目所装 Angular 版本中哪些 API 存在、哪些已稳定。查找组件、指令、管道或服务的使用位置,以及某个输入在何处被绑定。
适用场景
适合在 Angular 代码库中工作的助手,用来替代整份读取组件文件或 grep 选择器;也适合在建议某个 API 之前确认它在项目所用 Angular 版本中是否存在。对大型组件和 monorepo 收益最大;小组件的契约可能比源码还长。
运行要求
以 npm 包形式通过 stdio 在本机运行,可用 npx 或全局安装启动。仅服务器进程需要 Node 18.20.8 或更高版本。需要一个带 tsconfig 的 Angular 工作区;首次诊断或定义调用会把项目载入 Angular 语言服务器,可能耗时约一分钟。可选环境变量 NG_TOKEN_SAVER_IDLE_MS、NG_TOKEN_SAVER_PREWARM 和 NG_TOKEN_SAVER_TRACE。
安装前请注意
工具为只读分析,README 称不会写入项目文件。NG_TOKEN_SAVER_PREWARM=1 在空闲关闭前可能占用约 1 GB 内存。NG_TOKEN_SAVER_TRACE 会把原始语言服务器通信追加写入文件,其中可能包含源码路径和代码。README 自身的整段会话测量未发现总体节省 token,单次调用的节省不一定降低费用。

安装

在 SourceWeft 中

  1. 打开 控制台中的 Angular token saver,将其添加到工作区。
  2. 为需要使用其工具的对话启用该服务。

Desktop only,通过 STDIO。 STDIO 服务会启动本地进程,因此需要 SourceWeft 桌面宿主。

其他 MCP 客户端

参照 仓库 中的启动说明。

README

ng-token-saver

[npm version] [weekly downloads] [node] [license]

An MCP server that lets an AI agent understand Angular templates by asking the same compiler that builds the project, instead of guessing from file text. The token saving is measured, not promised.

Angular ships a first-class language server, but no official AI integration exposes it — the Angular CLI MCP (ng mcp) works at the docs-and-build level and does not touch templates. This server is that missing layer, and it answers for the Angular version the project actually runs.

Everything below marked as measured was produced by running code against six real Angular workspaces (17.3.12, 18.2.14, 19.2.25, 20.3.26, 21.2.18, 22.0.8) and two production projects. Every number can be reproduced with the commands in Reproducing the measurements.

Measured on a production Nx monorepoResult
A component's contract instead of its whole file67% fewer tokens over 1298 components
Where one input is bound on a component used 577 times50 527 → 1 035 tokens against the grep path
Errors of one template81 tokens, 1 ms warm against a 395-token compiler listing
Whole Claude Code sessions, five read-only questions × 3no saving: +15% input tokens, −4% cost, 60 of 60 answers right in every arm — why

The last row stays in the table: a per-call saving is not a per-session one, and the difference is explained below.

Quick start

The language server ships as a regular dependency — nothing to install besides the package:

npm install -g @alex-apps/ng-token-saver

Claude Code:

claude mcp add ng-token-saver -- ng-token-saver

Or, in Claude Code, as a plugin — the same server through npx, plus the one-line hints toward it; no global install needed:

/plugin marketplace add Alex88Ryabov/alex-apps-ng-token-saver/plugin install ng-token-saver@ng-token-saver

A server already registered with claude mcp add would then run twice; remove it with claude mcp remove ng-token-saver. The plugin's tools carry a plugin prefix (mcp__plugin_ng-token-saver_ng-token-saver__…), so permission rules and agent tool lists written for the bare names need the new ones.

Codex CLI:

codex mcp add ng-token-saver -- ng-token-saver

Any other MCP client:

json
{ "mcpServers": { "ng-token-saver": { "command": "ng-token-saver" } } }

Or skip the install and let the client fetch it through npx:

json
{ "mcpServers": { "ng-token-saver": { "command": "npx", "args": ["-y", "@alex-apps/ng-token-saver"] } } }

In Cursor that npx form is one click:

[Add to Cursor]

The npm and npx paths are verified by running: the packed tarball (79 kB, dist only) was installed into a clean prefix and all four tool kinds answered through a real MCP client, and the npx form connects in 1.2–2.0 s from a warm npm cache (the very first run on a machine also downloads the dependency tree — the language server alone unpacks to 13.6 MB).

A first question to ask it — the contract of a component whose members are scattered across an extends chain. Asked for fixtures/v17/src/app/derived-card.component.ts (a fixture in this repository), ng_component_info answers, verbatim:

json
{"found":true,"angularVersion":"17.3.12","className":"DerivedCardComponent","kind":"component","selector":"app-derived-card","standalone":true,"inlineTemplate":true,"styleUrls":[],"imports":[],"hostDirectives":[],"extends":"BasePanel","ancestors":[{"name":"BasePanel","file":"<repo>\\fixtures\\v17\\src\\app\\base-panel.ts"},{"name":"BaseWidget","file":"<repo>\\fixtures\\v17\\src\\app\\base-widget.ts"}],"inputs":[{"name":"accent","type":"boolean"},{"name":"heading","type":"string"},{"name":"disabled","type":"boolean"}],"outputs":[{"name":"blurred","type":"void"}],"publicMembers":[{"name":"focus","kind":"method","signature":"focus(): void","noop":true},{"name":"collapse","kind":"method","signature":"collapse(animated: boolean): void","noop":true}]}

811 characters with this checkout's absolute paths in place of <repo>, 305 ms on the session's first call (it loads the project's own TypeScript), single-digit milliseconds after. The asked file declares one input and an extends clause; heading, disabled, the output and both methods live in BasePanel and BaseWidget and are resolved statically, with their files named in ancestors for the next edit. "noop": true on focus() is the subclass shadowing it with an empty body — the kind of fact that otherwise costs a whole file read per ancestor.

Configs for Cursor, VS Code, Windsurf, Codex CLI and JetBrains, the Node floor, and running from source are in Requirements and setup.

The two problems it solves

1. No template awareness. grep over an .html file cannot tell you where {{ user().fullName }} is declared, and no amount of reading gives you TS2339 Property 'emailAddress' does not exist on type 'UserVm'. That is compiler output, not text.

2. Version drift. The AI context files on angular.dev (llms.txt) describe only the newest major and carry no version markers; the versioned archive sites serve none at all. On v17–v21 they hand the agent instructions that produce APIs which do not exist. Measured examples are in Version facts.

Tools

Six tools, 1040 characters of descriptions in total. Answers are dense JSON with no markdown.

ToolWhat it answersNeeds the language server
ng_template_definitionwhere a symbol on a template line is declared — the line as Read shows it, the symbol by nameyes
ng_template_diagnosticsAngular compiler errors for a template, or for a files batch; an entry anchored in the companion .ts carries file, a message repeated on several lines comes once with its linesyes
ng_component_infothe public contract of a component or directiveno
ng_workspace_mapprojects, versions, strictTemplates and zone.js per projectno
ng_version_ruleswhat exists and what does not in this project's Angular versionno
ng_find_usageswhere a component, directive, pipe or service is used; with input — where that input is boundno

Four of the six never start the language server, so they answer in milliseconds and keep working on workspaces where the server refuses to load.

Since 0.2.0 every position is 1-based, as Read shows it: ng_template_definition takes the line that way and the symbol by name (character is an alternative for a name that repeats on the line). 0.1.x took a 0-based line and character, the LSP convention — the same numbers now point one line lower.

Measured: contract instead of the whole file

ng_component_info returns the public contract of a component rather than its source. Measured across two production codebases through a real MCP client:

Nx monorepoCLI workspace*
Angular / TypeScript19.2.18 / 5.8.317.3.8 / 5.3.3
Components in the tally1298407
Parse errors00
Sources5 404 708 chars1 735 223 chars
Contracts (base-class members included)1 759 331 chars463 563 chars
Saved67%73%
Saved in tokens (o200k_base proxy)67%71%
Contract shorter than source1201 of 1298 (93%)386 of 407 (95%)
Flagged as partial1 of 12983 of 407
First call (loads the project's TypeScript)306 ms564 ms

* measured with the pre-0.1.2 wire format; the current format is leaner, so this saving is a floor.

The largest component in the monorepo shrinks from 177 863 to 10 770 characters while listing 117 contract members. Contracts include members inherited from base classes — the extends chain is resolved through relative imports, tsconfig path aliases and barrels. Before that resolver, 91 of 1298 monorepo contracts were flagged as partial; now 1 is.

Three caveats that travel with these numbers:

  • Tokens are counted through a proxy — OpenAI's o200k_base, since Claude's tokenizer is not public; cl100k_base agrees within one point on this data. Characters are exact.
  • The baseline is reading the whole file, which is what an agent does by default.
  • JSON tokenizes slightly worse than TypeScript, so token savings sit a point or two below character savings. The table carries both.

On small components there is no saving at all: a 17-line component produces a 578-character contract against a 315-character source. The contract grows with the number of members, the source with method bodies — and on production code the second wins almost always.

Measured: rename and diagnose

Renaming an input across usages. The grep path an agent actually takes — read the component file to learn the selector, then grep the selector and the binding spellings repo-wide — against ng_component_info plus ng_find_usages with its input filter, which returns only the tags that bind the name, each entry pointing at the binding itself. On the production monorepo, 6243 files scanned:

Componentgrep pathbridgesaved (o200k)
577 usages, mask bound on 5 tags50 527 tokens1 035 tokens98%
466 usages, icon bound on 463 tags41 698 tokens22 566 tokens46%
1211 usages, name bound on 1134 tags129 227 tokens30 650 tokens76%*

* the tool returns at most 500 entries per answer, and the answer says so.

The saving is decided by how many of the usages actually bind the input: mask is bound on 5 of 568 tags, and grep still prints every selector line plus 67 binding-shaped lines from across the repo — 62 of them somebody else's mask — while the bridge answers with exactly those five sites.

Diagnosing a template that will not compile. A whole-project compiler listing costs 395 tokens and 1321 ms; one ng_template_diagnostics call answers with the asked file's diagnostics in 81 tokens, 1 ms warm. The gap only widens with project size: the listing grows with the project, the answer does not. After an edit, fresh diagnostics arrive as a 340–400 ms push — against a rebuild.

Measured: whole sessions

The numbers above are per call. Whether they reach the bill was measured on whole sessions: five read-only questions on the production monorepo — an inherited contract, a plain contract, where one input is bound, where a component is used, which APIs the installed version has as stable — each answered three times by claude -p (Claude Code 2.1.322, claude-opus-5-5) in four arms, isolated from the machine's own CLAUDE.md, memory, hooks and MCP servers, with read-only tools and no subagents. Every one of the 60 answers was right.

ArmInput tokensOutput tokensCost*Turns
A — no server1 322 30620 560$1.2765
B — no server, told to read only what the question needs1 347 28021 062$1.3970
C — B plus this server1 552 42921 634$1.3483
D — C plus the plugin hints1 537 52820 828$1.2379

* Claude Code's own estimate at API list prices; cached input is cheap, so cost and token totals move apart.

Against the control (C versus B) the server added 15% input tokens and saved 4% of cost — inside the run-to-run spread, which reaches 3× within a single cell. Two reasons, both visible in the logs. Claude Code defers MCP tools, so the first call costs an extra ToolSearch turn, and every turn re-sends some 20 000 tokens of context. And on questions like these the agent spends little on files: for the inherited contract it read the 348-line component whole but grepped its 671-line base class for decorators — a few thousand tokens, which one extra turn outweighs.

The per-call savings hold where the files are large and read whole. In 81 field transcripts on the same monorepo agents read a component or directive file whole 319 times against 99 contract calls, and 254 of those reads came from subagents — see Hints in Claude Code. Whether the hint turns those reads into contract calls is not measured yet. Edits, refactors and builds were not part of this run.

Version facts

ng_version_rules contains no rule taken from documentation: the data comes from importing the packages actually installed in each fixture and from running the compiler.

The zoneless provider is renamed between v19 and v20.

APIv17v18v19v20v21v22
provideExperimentalZonelessChangeDetection–yesyes–––
provideZonelessChangeDetection–––yesyesyes

Advice to "enable zoneless" without a version breaks on three majors out of six.

Existing is not the same as ready. The @experimental and @developerPreview tags live only in declaration JSDoc and are invisible at runtime:

APIv17v18v19v20v21v22
input, output, model, viewChild, contentChildpreviewpreviewstablestablestablestable
effect, toObservablepreviewpreviewpreviewstablestablestable
linkedSignal, afterRenderEffect––previewstablestablestable
resource, rxResource, httpResource––experimentalexperimentalexperimentalstable

So "rewrite @Input() as input()" on a v17 or v18 project means moving to a non-public API, and resource() was experimental all the way through v21. A batch of signal APIs appears exactly at v19: linkedSignal, resource, rxResource, httpResource, afterRenderEffect, provideAppInitializer.

Two documentation claims that measurement contradicted: standalone becomes the default at v19, not v20; and *ngIf is not removed in 22.0.8 — it reports hint TS6385 (TypeScript's deprecation hint) and keeps working, with NgIf still exported from @angular/common.

Compiler gates, read in the 22.0.8 bundle and confirmed by running it — keyed on the project's Angular version, which the server detects from @angular/core next to the tsconfig (--angularCoreVersion is passed too, as a fallback):

FeatureGate
@if / @for / @switch blocks≥ 17.0.0
signals in two-way bindings≥ 17.2.0-0
@let≥ 18.1.0
implicit standalone≥ 19.0.0
DOM event type assertion≥ 20.2.0

Also measured: Signal Forms (@angular/forms/signals) exist only from v21 and are stable on 22.0.8; AbstractControl.events from v18; TestBed.tick from v20.

Outside the measured v17–v22 range ng_version_rules returns nothing and says so — extrapolating "it was in v22, so it is in v23" is exactly the failure it exists to prevent.

Honesty as a feature

An incomplete answer says so, in words, inside the answer:

  • A contract merges base-class members and host-directive exposures, resolved statically through relative imports, tsconfig aliases and barrels. Where the walk cannot continue — a base class from a package, a mixin call — the answer carries incomplete, naming the class and the file to ask about next.
  • ng_version_rules reports notMeasured topics, and a caveat when your minor differs from the measured one.
  • ng_find_usages labels declarations as declaration, admits when class-name matches were found without resolving imports, and names selector twins — a second declaration of the same selector elsewhere in the workspace — instead of silently mixing their usages.
  • ng_template_diagnostics separates three states that all look like an empty list: the template is clean; the server is silently down (caught by a canary probe); or template checking is off for this project — then the answer carries checksDisabled naming the tsconfig responsible. In the measured monorepo strictTemplates is off in two of seven applications, so the distinction is not theoretical.

What this is not

  • Not better than a careful grep at finding usages. grep -rn "<app-widget" finds the same 62 usages. What ng_find_usages adds: the selector and class name are derived from the file for you, usage kinds are labelled, all four attribute-binding spellings are covered, and path scopes the scan — 33 selectors in the measured monorepo are declared in two applications at once, and an unscoped search would mix them.
  • Not a replacement for the Angular CLI MCP — a different layer. ng mcp covers docs, best practices and build orchestration; none of its nine tools touches templates or the language server. The two complement each other.
  • Not a type checker of its own. The LSP-backed tools deliver the project's own compiler output, undistorted.

Known gaps are recorded, not hidden: a base class from a package or behind a mixin call stops the ancestor walk (1 of 1298 components in the measured monorepo), Nx projects with inferred targets come without tsConfig, and pipe twins are not detected.

Requirements and setup

  • Node ≥ 18.20.8 — the measured floor: the published package answered on clean Node 18.20.8, 20.20.2 and 22.x. This is about the MCP server process only — your project keeps building on its own Node. To give just the server a newer runtime, point the client config at that binary: "command": "C:\\node22\\node.exe".

From source (instead of npm):

  • The project's own dependencies: npm install, then npm run build.
  • The shipped language-server branch lives in tools/servers/ls22 and needs npm ci there once.
  • In every client config, replace the ng-token-saver command with node <path>/dist/index.js; for Claude Code: claude mcp add ng-token-saver -- node <path>/dist/index.js.

node_modules folders are not committed, including the twelve inside the stand. To restore the full measurement environment:

npm install && npm run buildcd tools/servers/ls22 && npm ci        # the branch actually shippedcd fixtures/v22 && npm ci              # repeat per fixture you want to run

Clients

The server is a plain stdio MCP server with no client-specific features, so any MCP client can launch it; installation and Claude Code registration are in Quick start. Usage guidance for the agent travels in the MCP instructions field — see Using with agents.

Cursor — the one-click button in Quick start, or the same mcpServers JSON as in Quick start, in ~/.cursor/mcp.json (all projects) or .cursor/mcp.json (one project).

Windsurf — the same JSON, in ~/.codeium/windsurf/mcp_config.json.

VS Code (Copilot agent mode) — .vscode/mcp.json; the key is servers and the entry takes a type:

json
{ "servers": { "ng-token-saver": { "type": "stdio", "command": "ng-token-saver" } } }

Codex CLI — codex mcp add ng-token-saver -- ng-token-saver, or ~/.codex/config.toml:

toml
[mcp_servers.ng-token-saver]command = "ng-token-saver"

JetBrains AI Assistant / Junie — Settings → Tools → AI Assistant → Model Context Protocol accepts the same JSON as Quick start's; for Junie, additionally enable "Pass custom MCP servers".

Configuration, all variables optional:

  • NG_TOKEN_SAVER_IDLE_MS — a language-server session unused this long shuts its ngserver down; the next call pays the cold start again. Default 900000 (15 minutes); 0 keeps sessions alive until the server exits. A session with a call in flight is never shut down.
  • NG_TOKEN_SAVER_PREWARM=1 — ng_workspace_map with a path inside an app starts loading that app into the language server in the background, so the first diagnostics or definition call finds it ready: 21 s → 1.4 s on the production monorepo. The cost is ~1 GB of memory until the idle shutdown, whether or not an LSP tool follows; a folder holding several projects (a workspace root, an Nx apps/) is not warmed, since which app to load is unknown.
  • NG_TOKEN_SAVER_SERVERS_DIR — where the language-server branch lives, if not in tools/servers next to the build.

Using with agents

The server sends its usage guidance in the MCP instructions field (924 characters), which Claude Code keeps in the agent's context even when tool descriptions are deferred until a tool search (checked on Claude Code 2.1.282: the whole text arrives while the tools show only their names). For a client that ignores instructions, the same text goes into CLAUDE.md or AGENTS.md:

Angular tools that answer from the compiler and the source instead of whole files. Prefer them to reading and grepping: ng_component_info for what a component or directive accepts (inputs, outputs, members, inherited ones included) instead of reading its .ts; ng_find_usages for where a component, directive, pipe or service is used, and with input for where one input is bound, instead of grep; ng_template_diagnostics after editing a template instead of ng build; ng_template_definition for what a template symbol is; ng_version_rules before suggesting an Angular API; ng_workspace_map once for projects, versions and strictTemplates. The first diagnostics or definition call in a workspace loads the project into the Angular language server and takes up to a minute on a large workspace; later calls take milliseconds, so a slow first answer is not a hang. Lines and characters are 1-based everywhere, as Read shows them.

Hints in Claude Code

The instructions alone did not change the habit. Counted with npm run bench:adoption over 81 Claude Code transcripts on the production monorepo, with the server installed and these instructions in context:

Main sessions (53)Subagents (28)
ng_component_info calls7029
Component files read whole (Read, cat, Get-Content), pre-edit Reads left out53254
ng_find_usages calls6759
Greps for a component element6611
ng_template_diagnostics calls / ng/nx builds112 / 1513 / 0

Subagents are where the gap is, and a capture of Claude Code's own requests shows why: a subagent receives the MCP instructions only after its first tool call, so its first move is made without them. ng_template_definition was not called once in these transcripts, and ng_version_rules twice.

The plugin's hook (plugin/hooks/hints.mjs) targets exactly these calls, and the counts above use its own definition of them. Before a component or directive file is read in full, an element selector is grepped, or an ng/nx build runs inside an Angular workspace, it adds one line naming the tool that answers it — once per agent and kind; the call itself runs unchanged. A subagent gets a one-sentence pointer before its first prompt. The line arrives next to the tool result, so it steers the next call rather than this one. if filters keep the hook off unrelated commands; where it does run it costs about 95 ms, most of it Node's start.

Reproducing the measurements

npm test                                  build plus 192 unit tests (node:test, no dependencies)npm run smoke                             end-to-end check with a real MCP client over stdionpm run bench:settle                      whether a pause after didOpen is needed (it is not)npm run bench:standalone                  where standalone becomes the default (v17..v22)npm run bench:api                         which Angular APIs exist in which majors, and their stabilitynpm run bench:contract <project root>     contract size against reading whole files (--tokens adds token counts)npm run bench:rename <component> <input>  the grep path against the bridge for an input renamenpm run bench:diagnose                    a compiler listing against one diagnostics callnpm run bench:matrix                      resolution probes across a fixturenpm run bench:negative                    what the server returns when things breaknpm run bench:didchange                   diagnostics timing after an editnpm run bench:adoption <transcripts dir>  tool calls against the habits they replace, in Claude Code transcriptsnpm run bench:session <tasks.json>        whole-session A/B through claude -p, four arms (see the file's header)

The whole-session tasks name files of a production project, so the tasks file is not in the repository; tools/bench-session.mjs documents its format, and any workspace will do.

The stand is fixtures/v17..v22 — six real Angular workspaces, each with its own node_modules and its own pinned TypeScript, plus fixtures/negative/* for failure cases.

Status

All six tools verified on the six fixtures and on two production codebases — 1298 and 407 components, zero parse errors — plus one Angular 16 project to check that out-of-range refusals are structured rather than silent. 192 unit tests, all green.

Measured latency: the two LSP-backed tools pay 8–28 s of cold start on the first call and answer in 2–9 ms after it; the four static tools answer in 250–600 ms on the first call and in milliseconds once the project's TypeScript is cached. A session idle for 15 minutes shuts its language server down, and the next call pays the cold start again — see NG_TOKEN_SAVER_IDLE_MS above.

License

GPL-3.0-or-later — see LICENSE. Copyright (C) 2026 Alex Ryabov. Use and modify freely; derivative works must stay open under the same license.

来源:README.md,提交 7701205

工具

0
SourceWeft 尚未在沙箱中启动过该软件包,因此其工具未知。

版本历史

2
  1. v0.2.0最新Sep 25, 2026
  2. v0.1.7Sep 16, 2026

评分

已满足适用检查项的 50%

该评分衡量此收录条目的完整程度,依据注册中心条目、端点与公开来源计算得出。它不是对服务器本身的评价,也不表示服务器安全或当前可用:可连通性是带日期的检查结果,评分也不包含安装量或用户评价。

  • 近 30 天内可连通25 分

    请保持端点能够响应 MCP 握手;SourceWeft 每 30 天探测一次。

  • 已声明认证方式10 分

    请在注册中心条目中声明凭据请求头,或保持端点能够响应探测,以便判定其认证方式。

  • 已列出工具15 分

    请让服务器在无凭据时响应 tools/list,或发布可在沙箱中无凭据启动的软件包。

  • 描述必需15 分
  • 图标10 分
  • 文档15 分
  • 许可证10 分