Engineering TokenSave: Semantic Code Analysis
- TokenSave
- Rust
- MCP
- code analysis
Over the past few weeks, I have been working as a maintainer of TokenSave, an open-source project originally created by Enzo Lombardi that provides semantic code intelligence to AI coding agents.
The idea behind TokenSave is relatively simple: instead of repeatedly asking a language model to explore a codebase using textual searches and file reads, give it access to a structured representation of the software it is working on.
Implementing this reliably, however, is a considerably more complex engineering problem.
My contributions have covered several layers of the project, from symbol resolution and database consistency to agent integrations, security, language support and release engineering.
This article describes selected contributions merged as of November 29, 2026.
Contents
- Beyond textual search
- Improving the accuracy of symbol resolution
- Evaluating SCIP interoperability
- Bringing deeper support to the .NET ecosystem
- Understanding build context
- Integrating with the AI coding ecosystem
- Preserving shell command semantics
- Concurrency, Git worktrees and index consistency
- Security and permission boundaries
- Making Windows a first-class platform
- Release engineering and maintainability
- What maintaining TokenSave has taught me
- Looking ahead
- Resources
Beyond textual search
AI coding agents frequently rely on tools such as grep, ripgrep and direct file reads to understand unfamiliar codebases.
These tools are effective, but textual matches alone cannot reliably explain relationships between software components.
A function name can appear in several modules, a method can belong to multiple classes and a reference can have different meanings depending on its context.
TokenSave approaches this problem by maintaining a local semantic knowledge graph built from source code.
Its architecture combines:
- Rust for the core implementation.
- Tree-sitter for syntactic analysis.
- libSQL for local graph persistence and retrieval.
- The Model Context Protocol (MCP) for communication with AI agents.
- Incremental indexing to keep the graph synchronized with the source code.
An agent can query symbols, relationships, callers, dependencies and relevant source fragments without repeatedly exploring the entire repository.
The objective is not simply to reduce token consumption. It is to improve the quality of the information available to an agent before it makes an engineering decision.
Improving the accuracy of symbol resolution
One of the most interesting areas of my work has been symbol resolution.
Extracting a function call from a syntax tree is relatively straightforward. Determining which function that call actually references is much harder.
Consider the following Rust example:
impl Cache {
fn clear(&mut self) {
self.entries.clear();
}
}
A resolver relying too heavily on name similarity could incorrectly associate the call to self.entries.clear() with Cache::clear() itself.
The resulting graph would contain a relationship that does not exist in the actual program.
Incorrect relationships can subsequently affect dependency analysis, impact analysis and the context returned to an AI agent.
In PR #1124, I restricted several fallback resolution strategies and improved the treatment of receiver expressions, qualified paths, trait declarations and Rust type references.
The changes were evaluated against SCIP reference data.
| Repository | Before | After |
|---|---|---|
| serde_json | 65.4% | 85.6% |
| toml_edit | 73.0% | 91.5% |
Recall also improved on both measured repositories.
These results apply to the specific evaluation workloads rather than every supported language or repository.
The important design principle is that leaving a relationship unresolved can be preferable to confidently returning an incorrect one.
For an AI agent, a misleading graph edge can be more expensive than a missing edge.
Evaluating SCIP interoperability
Tree-sitter provides an excellent foundation for multi-language syntactic analysis, but syntax alone cannot always reproduce compiler-level semantic information.
I explored the potential integration of SCIP, the Source Code Intelligence Protocol, as a complementary source of information.
The work included:
- A read-only comparison prototype.
- Project-level opt-in configuration.
- Validation against pinned Rust and TypeScript fixtures.
- Transactional insertion of proposed relationships into disposable graphs.
- Preservation of existing bindings and relationship provenance.
In PR #1113, the fixture evaluation successfully inserted 20 proposed Rust relationships and nine TypeScript relationships.
Both databases grew by 8 KiB. Median insertion transaction times were 0.90 ms and 0.65 ms respectively, across three fresh runs per fixture.
These measurements concern small, controlled fixtures. They do not establish production-scale performance or the cost of complete MCP queries.
The prototype also helped identify weaknesses in the existing resolver, independently of whether SCIP ultimately becomes part of the production indexing pipeline.
Full runtime integration and incremental invalidation remain separate engineering decisions.
Bringing deeper support to the .NET ecosystem
My professional experience includes maintaining C# and .NET applications, including desktop software used in embedded and industrial environments.
These applications often contain important relationships that cannot be discovered through ordinary function and class indexing alone.
A typical .NET application may contain:
- C# source code.
- XAML user interfaces.
- RESX localization resources.
- MSBuild project definitions.
- Application configuration files.
- SQL embedded in string literals.
Understanding such an application requires looking beyond individual programming-language constructs.
I contributed a series of improvements to extend TokenSave’s understanding of these environments.
Resources, localization and configuration
In PR #1177, I introduced bounded .NET discovery queries capable of identifying resource keys, missing translations, potentially unused resources and configuration key names.
The implementation deliberately omits configuration values and treats dynamic references as uncertain.
For localization analysis, identifying a potentially unused resource is not equivalent to proving that the resource is unreachable. Reflection, dynamic resource lookup and runtime configuration can all affect the result.
The interface therefore exposes candidates rather than presenting heuristic findings as compiler-proven facts.
XAML and C# relationships
In desktop applications built with WPF or Avalonia, relationships between user interfaces and application logic frequently cross file-format boundaries.
A XAML file can reference a C# code-behind class, event handler or view-model property.
A useful code intelligence system needs to understand these relationships instead of treating the markup and source code as isolated documents.
My contributions in PR #1202 and PR #1207 extended the resolution of explicit XAML bindings, code-behind classes and event handlers.
The implementation uses scoped type information and qualified names to improve resolution without claiming to reproduce every possible runtime binding.
I subsequently introduced an internal framework-dispatch boundary in PR #1208, separating framework-specific reference handling from general resolution.
An important distinction is whether a framework does not recognize a reference at all or recognizes it but cannot determine a unique target.
Treating those two cases differently helps prevent an overly permissive generic fallback from creating incorrect relationships.
Embedded SQL discovery
Another interesting problem is the discovery of SQL queries embedded in C# applications.
SQL statements may appear in ordinary strings, verbatim strings, raw strings or concatenated expressions.
In PR #1210, I added structured SQL discovery through the .NET CLI and MCP interfaces.
The implementation reports source locations, enclosing symbols, parse status and candidate database relationships without executing queries or connecting to a database.
It also distinguishes recognizable dynamic expressions and omits SQL bodies and literal values from the results.
Each SQL expression is bounded to 4 KiB, alongside limits on recursion, scanning and returned references.
The result is a static discovery mechanism, not a complete database dependency analyzer.
Understanding build context
A source file existing in a repository does not necessarily mean that it participates in a particular build.
This distinction is especially important in embedded software, where compilation may depend on the target architecture, product variant, compiler configuration or enabled features.
It is equally relevant in .NET projects, where source membership and conditional compilation depend on MSBuild configuration.
In PR #1209, I introduced static build-context discovery for MSBuild projects and existing CMake compilation databases.
The implementation reads build metadata on demand, while preserving the independence of ordinary source indexing.
Subsequent contributions extended this functionality with standard SDK compile membership in PR #1212 and configuration-scoped compiler-symbol evaluation in PR #1214.
For example:
#if DEBUG
const string Endpoint = "localhost";
#else
const string Endpoint = "production";
#endif
The relevance of each declaration depends on the selected compilation context.
Instead of treating every declaration as universally active, scoped discovery can evaluate supported project-level compiler symbols and conservatively handle uncertain cases.
The design avoids executing arbitrary build scripts or introducing a mandatory dependency on a complete build environment.
General MSBuild evaluation, SDK-injected symbols and fully configuration-specific graph resolution remain limitations.
Integrating with the AI coding ecosystem
An effective code intelligence engine is only useful if agents can reliably access it.
Different AI coding agents have different configuration formats, installation scopes, permission models and extension mechanisms.
I have worked extensively on integrations involving:
- Claude Code.
- OpenAI Codex CLI.
- GitHub Copilot.
- Herdr.
Much of this work involved handling the differences between global and project-local configuration.
For example, Codex and Copilot support environment variables that can relocate their configuration directories.
Assuming a default home directory can cause an integration to appear installed while the agent is actually reading an entirely different configuration.
I addressed these problems through PR #1186 and PR #1188.
I also implemented project-local MCP registration for Codex and Copilot.
Project-local registration allows integration settings to follow the repository rather than requiring identical global configuration across every development environment.
It does not bypass the agent’s trust model or imply that every agent hook can also be installed at project scope.
Preserving shell command semantics
TokenSave integrates with agent hooks to suggest semantic alternatives to traditional code searches.
However, intercepting shell commands introduces an important correctness problem.
Not every invocation of grep, rg or Select-String represents a search that can safely be replaced by a semantic query.
For example:
git diff | grep '^+'
This command filters Git output. It does not search for a symbol in a codebase.
Replacing it with a graph query would fundamentally change its behavior.
Several contributions addressed the distinction between semantic code discovery and legitimate textual operations, including pipelines, compound commands, regular expressions and searches reading standard input.
PowerShell introduces additional complexity through its own syntax, argument handling and command composition.
In PR #1173, I introduced syntax-tree-based classification for supported PowerShell searches.
The parser does not execute command text or launch subprocesses. Dynamic arguments, pipelines, parse errors and other ambiguous cases remain on the native execution path.
The guiding principle is that an optimization must not silently change the meaning of an operation.
Concurrency, Git worktrees and index consistency
Modern AI-assisted development increasingly involves multiple agents working on the same repository.
Git worktrees allow these agents to operate in independent checkouts, but they also introduce challenges around index ownership, initialization and branch consistency.
Two processes may attempt to initialize the same index simultaneously. Git hooks may trigger overlapping synchronization operations. Files may also be replaced with older copies without following the expected modification-time progression.
I worked on several aspects of these problems.
In PR #1018, together with another contributor, I introduced early serialization of Git hook-triggered synchronization.
Processes that fail to acquire the synchronization lock exit before opening the database or starting expensive indexing operations.
Stale locks are reclaimed only after confirming that the recorded process is no longer alive. Malformed or unreadable locks are preserved rather than deleted speculatively.
In PR #1199, I added checkout-local initialization coordination and documented a Herdr integration workflow.
Concurrent MCP servers starting against the same fresh checkout can reuse the first successful index initialization.
The operating-system-backed lock uses a bounded wait of 30 seconds and is released when its owning process exits.
A Windows smoke test using Herdr 0.9.5 and Codex successfully retrieved a source file through TokenSave. A separate linked-worktree test retrieved a file specific to that checkout.
These tests exercised the MCP integration directly rather than evaluating an entire model-driven development session.
Security and permission boundaries
Giving AI agents access to development tools introduces responsibilities beyond ordinary application security.
A tool capable of inspecting a repository should not automatically receive permission to modify it.
In PR #1092, building on a community-reported permission issue, I introduced a centralized classification of MCP tools and more restrictive generated approval policies.
Supported integrations generate exact read-only approvals by default, while write approvals require explicit opt-in.
Existing user grants are preserved during ordinary reinstalls and upgrades. Consequently, older broad permissions may remain active until explicitly reset.
This distinction matters because an application should neither silently expand an agent’s authority nor unexpectedly remove permissions that the user deliberately configured.
I also contributed to indexed-data security, MCP input validation and privacy controls.
Relevant work included MCP boundary hardening, strict read-parameter validation and telemetry opt-out controls.
Security is part of the architecture, not an optional layer added after implementing the main functionality.
Making Windows a first-class platform
Cross-platform Rust development does not eliminate operating-system-specific behavior.
Windows introduces particular challenges involving executable replacement, file locking, process permissions and installation mechanisms.
For example, attempting to upgrade TokenSave through Cargo while an MCP server is still running can produce:
error: failed to move tokensave.exe
Access denied (os error 5)
The executable cannot simply be treated like an ordinary replaceable file while another process is using it.
In PR #1204, I introduced a coordinated Windows upgrade helper.
It requests cooperative shutdown, waits for processes associated with the selected installation and supports explicitly authorized forced termination.
The previous executable is moved away from its launch path during the upgrade and restored if Cargo fails before installing a replacement.
The implementation scopes its operations to the selected installation rather than indiscriminately terminating every TokenSave process.
Local end-to-end verification was blocked by sandbox permissions, so the merged implementation includes Windows regression coverage and CI integration without claiming that the complete local upgrade flow was successfully verified.
Release engineering and maintainability
Maintaining open-source software involves considerably more than developing new features.
A release needs to be reproducible, installable, diagnosable and compatible with the environments in which users actually work.
My contributions have also included:
- Rust toolchain and dependency upgrades.
- Packaged CLI smoke tests.
- Installation-method-aware upgrades.
- Safe integration uninstallation.
- Build provenance and version diagnostics.
- Structured debugging and performance profiling.
- Database integrity checks.
- GitHub Actions and crates.io publication workflows.
These improvements reduce operational uncertainty for both maintainers and users.
On November 28, 2026, we published TokenSave 7.18.0 to crates.io.
The subsequent development work described in this article should not be confused with the exact contents of that release.
What maintaining TokenSave has taught me
TokenSave sits at the intersection of several engineering disciplines:
- Programming language analysis.
- Graph-based information retrieval.
- Database systems.
- Concurrent development workflows.
- Developer tooling.
- Security and permission management.
- AI-assisted software engineering.
Working on the project has reinforced the importance of explicit ownership, bounded resource consumption, conservative semantic analysis and measurable correctness.
It has also highlighted an interesting distinction between AI-assisted development and engineering software for AI agents.
Generating source code is only one part of the problem.
The surrounding infrastructure needs to provide reliable context, preserve user intent and expose predictable behavior when information is incomplete.
As AI agents become more capable, I believe that the quality of this infrastructure will become increasingly important.
Better models are useful. Better engineering tools allow those models to operate with more accurate information and fewer unnecessary operations.
Looking ahead
I see several interesting directions for the future of TokenSave:
- Deeper compiler-aware semantic analysis.
- Further modularization of the core architecture.
- More accurate framework and build-system intelligence.
- Cleaner agent integration boundaries.
- Improved indexing performance and memory efficiency.
- Continued work on security and cross-platform reliability.
These are areas of ongoing exploration rather than promises about functionality already delivered.
TokenSave is a collaborative open-source effort, and its evolution benefits from the contributions, bug reports and feedback of its community.
For me, it represents an opportunity to apply systems engineering principles to an emerging generation of software development tools.
The ultimate objective is not simply to make AI agents consume fewer tokens.
It is to help them understand software better.