@qmediat.io/gemini-code-context-mcp 1.0.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.
Files changed (120) hide show
  1. package/CHANGELOG.md +79 -0
  2. package/LICENSE +21 -0
  3. package/README.md +159 -0
  4. package/dist/auth/credentials-store.d.ts +47 -0
  5. package/dist/auth/credentials-store.d.ts.map +1 -0
  6. package/dist/auth/credentials-store.js +215 -0
  7. package/dist/auth/credentials-store.js.map +1 -0
  8. package/dist/auth/fingerprint.d.ts +8 -0
  9. package/dist/auth/fingerprint.d.ts.map +1 -0
  10. package/dist/auth/fingerprint.js +12 -0
  11. package/dist/auth/fingerprint.js.map +1 -0
  12. package/dist/auth/init-command.d.ts +9 -0
  13. package/dist/auth/init-command.d.ts.map +1 -0
  14. package/dist/auth/init-command.js +279 -0
  15. package/dist/auth/init-command.js.map +1 -0
  16. package/dist/auth/profile-loader.d.ts +28 -0
  17. package/dist/auth/profile-loader.d.ts.map +1 -0
  18. package/dist/auth/profile-loader.js +107 -0
  19. package/dist/auth/profile-loader.js.map +1 -0
  20. package/dist/cache/cache-manager.d.ts +78 -0
  21. package/dist/cache/cache-manager.d.ts.map +1 -0
  22. package/dist/cache/cache-manager.js +364 -0
  23. package/dist/cache/cache-manager.js.map +1 -0
  24. package/dist/cache/files-uploader.d.ts +42 -0
  25. package/dist/cache/files-uploader.d.ts.map +1 -0
  26. package/dist/cache/files-uploader.js +176 -0
  27. package/dist/cache/files-uploader.js.map +1 -0
  28. package/dist/cache/ttl-watcher.d.ts +21 -0
  29. package/dist/cache/ttl-watcher.d.ts.map +1 -0
  30. package/dist/cache/ttl-watcher.js +75 -0
  31. package/dist/cache/ttl-watcher.js.map +1 -0
  32. package/dist/config.d.ts +25 -0
  33. package/dist/config.d.ts.map +1 -0
  34. package/dist/config.js +34 -0
  35. package/dist/config.js.map +1 -0
  36. package/dist/gemini/client.d.ts +7 -0
  37. package/dist/gemini/client.d.ts.map +1 -0
  38. package/dist/gemini/client.js +19 -0
  39. package/dist/gemini/client.js.map +1 -0
  40. package/dist/gemini/model-registry.d.ts +25 -0
  41. package/dist/gemini/model-registry.d.ts.map +1 -0
  42. package/dist/gemini/model-registry.js +70 -0
  43. package/dist/gemini/model-registry.js.map +1 -0
  44. package/dist/gemini/models.d.ts +23 -0
  45. package/dist/gemini/models.d.ts.map +1 -0
  46. package/dist/gemini/models.js +98 -0
  47. package/dist/gemini/models.js.map +1 -0
  48. package/dist/index.d.ts +10 -0
  49. package/dist/index.d.ts.map +1 -0
  50. package/dist/index.js +55 -0
  51. package/dist/index.js.map +1 -0
  52. package/dist/indexer/globs.d.ts +25 -0
  53. package/dist/indexer/globs.d.ts.map +1 -0
  54. package/dist/indexer/globs.js +210 -0
  55. package/dist/indexer/globs.js.map +1 -0
  56. package/dist/indexer/hasher.d.ts +31 -0
  57. package/dist/indexer/hasher.d.ts.map +1 -0
  58. package/dist/indexer/hasher.js +61 -0
  59. package/dist/indexer/hasher.js.map +1 -0
  60. package/dist/indexer/workspace-scanner.d.ts +27 -0
  61. package/dist/indexer/workspace-scanner.d.ts.map +1 -0
  62. package/dist/indexer/workspace-scanner.js +77 -0
  63. package/dist/indexer/workspace-scanner.js.map +1 -0
  64. package/dist/manifest/db.d.ts +38 -0
  65. package/dist/manifest/db.d.ts.map +1 -0
  66. package/dist/manifest/db.js +223 -0
  67. package/dist/manifest/db.js.map +1 -0
  68. package/dist/server.d.ts +5 -0
  69. package/dist/server.d.ts.map +1 -0
  70. package/dist/server.js +117 -0
  71. package/dist/server.js.map +1 -0
  72. package/dist/tools/ask.tool.d.ts +34 -0
  73. package/dist/tools/ask.tool.d.ts.map +1 -0
  74. package/dist/tools/ask.tool.js +216 -0
  75. package/dist/tools/ask.tool.js.map +1 -0
  76. package/dist/tools/clear.tool.d.ts +15 -0
  77. package/dist/tools/clear.tool.d.ts.map +1 -0
  78. package/dist/tools/clear.tool.js +31 -0
  79. package/dist/tools/clear.tool.js.map +1 -0
  80. package/dist/tools/code.tool.d.ts +42 -0
  81. package/dist/tools/code.tool.d.ts.map +1 -0
  82. package/dist/tools/code.tool.js +327 -0
  83. package/dist/tools/code.tool.js.map +1 -0
  84. package/dist/tools/index.d.ts +3 -0
  85. package/dist/tools/index.d.ts.map +1 -0
  86. package/dist/tools/index.js +14 -0
  87. package/dist/tools/index.js.map +1 -0
  88. package/dist/tools/registry.d.ts +37 -0
  89. package/dist/tools/registry.d.ts.map +1 -0
  90. package/dist/tools/registry.js +16 -0
  91. package/dist/tools/registry.js.map +1 -0
  92. package/dist/tools/reindex.tool.d.ts +21 -0
  93. package/dist/tools/reindex.tool.d.ts.map +1 -0
  94. package/dist/tools/reindex.tool.js +62 -0
  95. package/dist/tools/reindex.tool.js.map +1 -0
  96. package/dist/tools/status.tool.d.ts +15 -0
  97. package/dist/tools/status.tool.d.ts.map +1 -0
  98. package/dist/tools/status.tool.js +105 -0
  99. package/dist/tools/status.tool.js.map +1 -0
  100. package/dist/types.d.ts +68 -0
  101. package/dist/types.d.ts.map +1 -0
  102. package/dist/types.js +5 -0
  103. package/dist/types.js.map +1 -0
  104. package/dist/utils/cost-estimator.d.ts +32 -0
  105. package/dist/utils/cost-estimator.d.ts.map +1 -0
  106. package/dist/utils/cost-estimator.js +83 -0
  107. package/dist/utils/cost-estimator.js.map +1 -0
  108. package/dist/utils/logger.d.ts +11 -0
  109. package/dist/utils/logger.d.ts.map +1 -0
  110. package/dist/utils/logger.js +21 -0
  111. package/dist/utils/logger.js.map +1 -0
  112. package/dist/utils/paths.d.ts +20 -0
  113. package/dist/utils/paths.d.ts.map +1 -0
  114. package/dist/utils/paths.js +41 -0
  115. package/dist/utils/paths.js.map +1 -0
  116. package/dist/utils/progress.d.ts +16 -0
  117. package/dist/utils/progress.d.ts.map +1 -0
  118. package/dist/utils/progress.js +47 -0
  119. package/dist/utils/progress.js.map +1 -0
  120. package/package.json +78 -0
package/CHANGELOG.md ADDED
@@ -0,0 +1,79 @@
1
+ # Changelog
2
+
3
+ All notable changes to `@qmediat.io/gemini-code-context-mcp` will be documented here.
4
+
5
+ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
6
+ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
+
8
+ ## [Unreleased]
9
+
10
+ ## [1.0.0] — 2026-04-19
11
+
12
+ First public release. An MCP server that wraps Google's Gemini API with persistent Context Caching so Claude Code (and other MCP hosts) can query large codebases with cached input tokens instead of re-sending the entire workspace on every prompt.
13
+
14
+ ### Added
15
+
16
+ - **Five core MCP tools**: `ask` (Q&A / long-context analysis), `code` (dedicated coding delegation with thinking budget + optional code execution), `status` (cache + cost telemetry), `reindex` (force cache rebuild), `clear` (drop cache and manifest).
17
+ - **Direct `@google/genai` SDK integration** with Files API + Context Cache. Uploads deduped by SHA-256 content hash; cache keyed by `(workspaceRoot, filesHash, model, systemPromptHash)`. Bounded concurrent upload pool (default 10 parallel) + same-batch hash dedup.
18
+ - **Dynamic model registry** with alias resolution (`latest-pro`, `latest-pro-thinking`, `latest-flash`, `latest-lite`). Resolves against the live `models.list()` at startup so new Gemini models are picked up without code changes. Filters out `image`, `tts`, `vision`, `audio` variants.
19
+ - **3-tier authentication**: Vertex AI via ADC → credentials file (chmod 0600 via atomic tmp+rename with random suffix, O_EXCL) → env var (with startup warning). `init` subcommand runs a guided interactive setup with hidden password input (SS3/OSC/CSI escape handling) and validates profile names against INI-injection while allowing Unicode.
20
+ - **Daily budget cap** (`GEMINI_DAILY_BUDGET_USD`) with hard-stop enforcement based on recorded usage metrics in SQLite.
21
+ - **TTL watcher** for background Context Cache refresh on "hot" workspaces (used within 10 minutes). Respects per-cache TTL; configurable via `GEMINI_CODE_CONTEXT_CACHE_TTL_SECONDS`.
22
+ - **SQLite manifest** (`better-sqlite3` WAL mode) tracking workspaces, file uploads, and usage metrics. FK cascades from workspaces → files on delete.
23
+ - **Workspace scanner** with SHA-256 content hashing (deterministic `localeCompare` sort for cache-key stability), POSIX path normalisation for Windows, gitignore-aware default excludes (`node_modules`, `.git`, build dirs), and dual include/exclude patterns supporting extensions (`*.go`, `.kt`) and literal filenames (`Dockerfile`, `Makefile`).
24
+ - **Self-healing on stale cache**: ask/code tools auto-invalidate and rebuild once on Gemini 404/NOT_FOUND against cached content. Retry preserves original error via `Error.cause` and reports `retriedOnStaleCache` in tool metadata.
25
+ - **In-process coalescing mutex** keyed on full cache fingerprint (workspaceRoot + filesHash + model + systemPromptHash + allowCaching + cacheMinTokens) prevents duplicate cache creation under concurrent tool calls.
26
+ - **Cost estimator** with per-model pricing defaults and runtime override via `GEMINI_PRICING_OVERRIDES` (JSON). Full-precision micros-to-dollars conversion so sub-cent calls are visible in `status`.
27
+ - **Configurable cache minimum tokens** (`GEMINI_CODE_CONTEXT_CACHE_MIN_TOKENS`) so users can adjust the 1024-token floor if Gemini changes it.
28
+ - **XDG compliance**: state files honour `XDG_STATE_HOME`; config files honour `XDG_CONFIG_HOME`. Falls back to `~/.qmediat/` and `~/.config/qmediat/` respectively.
29
+ - **Full docs**: getting-started, configuration, how-caching-works, migration-from-jamubc, architecture, security, cost-model, KNOWN-DEFICITS, ACCEPTED-RISKS, FOLLOW-UP-PRS.
30
+ - **Examples** for Claude Code, Claude Desktop, Cursor, and Vertex AI setups.
31
+ - **CI** matrix on Node 22 + Node 24 with TypeScript strict (including `exactOptionalPropertyTypes`), Biome lint/format, Vitest 4.x with real-Gemini integration tests (skipped without `GEMINI_API_KEY`).
32
+
33
+ ### Fixed (during v1.0 review cycle)
34
+
35
+ Integration-test-surfaced and review-surfaced fixes landed before the v1.0.0 release:
36
+
37
+ - **Gemini API incompatibility** — `generateContent({cachedContent, systemInstruction})` returns 400; the system instruction is baked into the cache at build time and must NOT be repeated on the generate call. Similarly `tools: [{codeExecution: {}}]` cannot coexist with `cachedContent` — `code({codeExecution: true})` now force-bypasses the cache. Integration test locked as regression anchor.
38
+ - **Windows path separator mismatch** — `path.relative()` returns `\` on Windows but our glob checks used `/`. Scanner now normalises every relpath to POSIX separators. Windows users would have silently over-indexed node_modules.
39
+ - **Cache URI format** — Files API returns `.name` (`files/abc123`) and `.uri` (full HTTPS URL); `fileData.fileUri` requires the full URI. Preferring `.uri` eliminates a 400 "Cannot fetch content from the provided URL".
40
+ - **FK constraint on first-time upload** — workspace row is upserted before file rows.
41
+ - **Cache reuse ordering** — reuse check runs before the token-floor check so small workspaces with valid caches keep them.
42
+ - **In-flight mutex scope** — keyed on full fingerprint instead of just workspaceRoot.
43
+ - **Post-retry telemetry** — `activePrep` tracks the context used for the final successful call so `cacheHit`, `cacheRebuilt`, `retriedOnStaleCache` reflect reality.
44
+ - **Credentials atomic write** — `crypto.randomBytes(8)` suffix + `O_EXCL` (`flag:'wx'`) defeats symlink-race attacks.
45
+ - **ANSI escape handling** — `askHidden` now correctly skips SS3 (F1-F4), OSC, DCS sequences instead of leaking bytes into the API key.
46
+ - **Process listener leak** — `SIGINT`/`exit` handlers removed on resolve/reject paths.
47
+ - **Windows cross-platform** — `execFileSync` replaces shell-redirection `execSync('git … 2>/dev/null')`.
48
+ - **Dotfiles-in-git detection** — git walk-up finds enclosing repo on fresh install.
49
+ - **Inline async reads** — `readFile` instead of `readFileSync`, with 20 MB aggregate size cap.
50
+ - **Sort stability** — `localeCompare` replaces the non-zero-returning comparator.
51
+ - **FK cascade** — redundant `DELETE FROM files` removed (cascade handles it).
52
+ - **Double stat** — scanner passes pre-fetched `Stats` into hasher.
53
+ - **SERVER_VERSION from package.json** at runtime.
54
+
55
+ ### Security
56
+
57
+ - API keys never logged in full (only `AIza...xyz9` fingerprint at first 4 + last 4 chars).
58
+ - Daily budget cap limits blast radius of leaked keys.
59
+ - Atomic write with `O_EXCL` on credentials file.
60
+ - INI profile names sanitised against syntax chars + control chars.
61
+ - Threat model documented in [`docs/security.md`](docs/security.md).
62
+
63
+ ### Performance
64
+
65
+ - Parallel Files API uploads (10 concurrent by default).
66
+ - Hash cache keyed on `(path, mtime, size)` avoids re-reading unchanged files.
67
+ - In-process mutex coalesces concurrent same-workspace prepareContext calls.
68
+ - Context Cache reduces repeat-query input tokens to ~25 % of uncached rate and latency from ~45 s to ~2 s on typical workspaces.
69
+
70
+ ### Known deficits (by design or deferred)
71
+
72
+ - TTL watcher cross-process coordination (documented in [`docs/KNOWN-DEFICITS.md`](docs/KNOWN-DEFICITS.md)).
73
+ - Pre-rebuild `caches.delete` loses cache on transient create failures ([`docs/ACCEPTED-RISKS.md`](docs/ACCEPTED-RISKS.md)).
74
+ - Key fingerprint format (accepted as industry standard).
75
+ - MIME type simplified to `text/plain` for all files.
76
+ - Unit test coverage gaps for cache-manager / files-uploader / ttl-watcher / profile-loader / parseEdits tracked in [`docs/FOLLOW-UP-PRS.md`](docs/FOLLOW-UP-PRS.md).
77
+
78
+ [Unreleased]: https://github.com/qmediat/gemini-code-context-mcp/compare/v1.0.0...HEAD
79
+ [1.0.0]: https://github.com/qmediat/gemini-code-context-mcp/releases/tag/v1.0.0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Quantum Media Technologies sp. z o.o. (qmediat.io)
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,159 @@
1
+ # `@qmediat.io/gemini-code-context-mcp`
2
+
3
+ > **Give Claude Code persistent memory of your codebase, backed by Gemini's 2M-token context.**
4
+ > Turn repeat code-review queries into second-scale responses — same codebase, same answers, a fraction of the cost.
5
+
6
+ [![npm version](https://img.shields.io/npm/v/@qmediat.io/gemini-code-context-mcp.svg)](https://www.npmjs.com/package/@qmediat.io/gemini-code-context-mcp)
7
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](./LICENSE)
8
+ [![TypeScript strict](https://img.shields.io/badge/TypeScript-strict-blue.svg)](./tsconfig.json)
9
+ [![Node ≥22](https://img.shields.io/badge/node-%3E%3D22-brightgreen)](./package.json)
10
+
11
+ ---
12
+
13
+ ## Why this server?
14
+
15
+ An MCP (Model Context Protocol) server that wraps Google's Gemini API with **persistent context caching** for MCP hosts like Claude Code, Claude Desktop, and Cursor.
16
+
17
+ | | [jamubc/gemini-mcp-tool](https://github.com/jamubc/gemini-mcp-tool) | **`@qmediat.io/gemini-code-context-mcp`** |
18
+ |---|---|---|
19
+ | Maintenance | Abandoned (last release 2025-07) |Actively maintained |
20
+ | Default model | Hardcoded `gemini-3.1-pro-preview` |Dynamic `latest-pro` alias — auto-upgrades with every Gemini release |
21
+ | Backend | Shells out to `gemini` CLI (~200 ms spawn overhead) |Direct `@google/genai` SDK |
22
+ | Repeat queries | Re-sends entire codebase every call |**Files API + Context Cache** — repeat queries reuse the indexed codebase, cached input tokens billed at ~25 % of the uncached rate |
23
+ | Coding delegation | Legacy prompt-injection `changeMode` |Native `thinkingConfig` + optional `codeExecution` |
24
+ | Auth | Key in `~/.claude.json` env var |3-tier: ADC / credentials file (chmod 0600) / env var (+ warning) |
25
+ | Cost control | — |Daily budget cap in USD (`GEMINI_DAILY_BUDGET_USD`) |
26
+ | Dead deps | 5 unused packages (`ai`, `chalk`, `d3-shape`, …) |Zero dead deps |
27
+
28
+ ## Quick start
29
+
30
+ ```bash
31
+ # 1. Secure credential setup (your key never touches ~/.claude.json)
32
+ npx @qmediat.io/gemini-code-context-mcp init
33
+
34
+ # 2. Paste this into ~/.claude.json (or Claude Desktop / Cursor config)
35
+ {
36
+ "mcpServers": {
37
+ "gemini-code-context": {
38
+ "command": "npx",
39
+ "args": ["-y", "@qmediat.io/gemini-code-context-mcp"],
40
+ "env": { "GEMINI_CREDENTIALS_PROFILE": "default" }
41
+ }
42
+ }
43
+ }
44
+
45
+ # 3. Restart your MCP host. Ask Claude:
46
+ # > Use gemini-code-context.ask to summarize this codebase
47
+ ```
48
+
49
+ First query: ~30–45 s (scan + upload + cache build). Every follow-up: ~2–3 s.
50
+
51
+ See [`docs/getting-started.md`](./docs/getting-started.md) for a 3-minute walkthrough.
52
+
53
+ ## Tools
54
+
55
+ | Tool | What it does |
56
+ |---|---|
57
+ | **`ask`** | Q&A and long-context analysis against your workspace. Uses persistent context cache. |
58
+ | **`code`** | Delegate a coding task to Gemini with native thinking budget (16 k default) and optional sandboxed code execution. Returns structured OLD/NEW diffs Claude Code can apply directly. |
59
+ | **`status`** | Inspect the cache state, available models, TTL remaining, cumulative cost. |
60
+ | **`reindex`** | Force a fresh cache rebuild for this workspace. |
61
+ | **`clear`** | Delete the cache and manifest for this workspace. |
62
+
63
+ All tools accept an optional `workspace` path (defaults to `cwd`), `model` alias or literal ID, and glob overrides.
64
+
65
+ ## Installation methods
66
+
67
+ | Method | Config |
68
+ |---|---|
69
+ | **npx (recommended)** | `"command": "npx", "args": ["-y", "@qmediat.io/gemini-code-context-mcp"]` |
70
+ | **Global install** | `npm install -g @qmediat.io/gemini-code-context-mcp` → `"command": "gemini-code-context-mcp"` |
71
+ | **Local dev** | `git clone …; npm install; npm run build` → `"command": "node", "args": ["/path/to/dist/index.js"]` |
72
+
73
+ ## How the caching works
74
+
75
+ ```
76
+ first call repeat calls
77
+ ┌──────────────────────────┐ ┌──────────────────────────┐
78
+ │ scan workspace │ │ scan workspace │
79
+ │ sha256 each file │ │ sha256 each file │
80
+ │ merge → files_hash │ │ merge → files_hash │
81
+ │ │ │ │
82
+ │ upload changed files → │ │ hash matches manifest │
83
+ │ Files API │ │ → reuse cached context │
84
+ │ │ │ │
85
+ │ caches.create(model, │ │ generateContent( │
86
+ │ contents, ttl=1h) │ │ cachedContent: ID, │
87
+ │ → cache_id │ │ contents: prompt │
88
+ │ │ │ ) │
89
+ │ │ │ │
90
+ │ generateContent( │ │ response in ~2 s at │
91
+ │ cachedContent: ID, │ │ ~25 % input cost │
92
+ │ contents: prompt │ │ │
93
+ │ ) │ │ │
94
+ └──────────────────────────┘ └──────────────────────────┘
95
+ ~35–45 s, full input price ~2–3 s, cached-token price
96
+ ```
97
+
98
+ Deep dive: [`docs/how-caching-works.md`](./docs/how-caching-works.md).
99
+
100
+ ## Configuration
101
+
102
+ Every env var, auth tier, and per-call override lives in [`docs/configuration.md`](./docs/configuration.md).
103
+
104
+ | Key vars | Default | |
105
+ |---|---|---|
106
+ | `GEMINI_CREDENTIALS_PROFILE` | `default` | Profile name in the credentials file |
107
+ | `GEMINI_API_KEY` | — | Fallback (Tier 3; emits a warning) |
108
+ | `GEMINI_USE_VERTEX` + `GOOGLE_CLOUD_PROJECT` | — | Enable Vertex AI backend |
109
+ | `GEMINI_DAILY_BUDGET_USD` | unlimited | Hard cap on daily spend |
110
+ | `GEMINI_CODE_CONTEXT_DEFAULT_MODEL` | `latest-pro` | Alias or literal ID |
111
+ | `GEMINI_CODE_CONTEXT_CACHE_TTL_SECONDS` | `3600` | Cache TTL |
112
+ | `GEMINI_CODE_CONTEXT_LOG_LEVEL` | `info` | `debug` / `info` / `warn` / `error` |
113
+
114
+ ## Migrating from `gemini-mcp-tool`
115
+
116
+ One-line change in `~/.claude.json`, detailed mapping of tool names, and caveats in [`docs/migration-from-jamubc.md`](./docs/migration-from-jamubc.md).
117
+
118
+ ## Security
119
+
120
+ - API key stored in `~/.config/qmediat/credentials` (chmod 0600), never in MCP host config
121
+ - Only a fingerprint (`AIza...xyz9`) appears in logs
122
+ - Daily budget cap enforced locally — bounds blast radius of a leaked key
123
+ - Zero telemetry by default; manifest stored locally in `~/.qmediat/`
124
+ - `code` tool's `codeExecution` runs in Google's sandbox, not on your machine
125
+
126
+ Full threat model + incident response: [`docs/security.md`](./docs/security.md).
127
+
128
+ ## Cost model
129
+
130
+ Projected savings vs uncached usage on a 500 k-token repo with 20 queries/day: up to **~60 % lower spend** with cache enabled, with repeat-query latency typically an order of magnitude lower than the first (uncached) call. Actual numbers depend on repo size, TTL, and query volume — we'll publish measured benchmarks after the first real-world deployments.
131
+
132
+ Per-tool cost breakdown, free-tier guidance, and all the knobs: [`docs/cost-model.md`](./docs/cost-model.md).
133
+
134
+ ## Architecture
135
+
136
+ ```
137
+ ┌──────────────┐ stdio ┌────────────────────────────────────┐ HTTPS ┌─────────────┐
138
+ │ Claude Code │◄─────────►│ @qmediat.io/gemini-code-context-… │◄─────────►│ Gemini API │
139
+ └──────────────┘ └────────────────────────────────────┘ └─────────────┘
140
+ │
141
+ ┌───────────┼───────────┬──────────────────┐
142
+ ▼ ▼ ▼ ▼
143
+ ┌───────────┐ ┌─────────┐ ┌──────────┐ ┌──────────────┐
144
+ │ Workspace │ │ Cache │ │ Manifest │ │ TTL Watcher │
145
+ │ Indexer │ │ Manager │ │ (SQLite) │ │ (background) │
146
+ └───────────┘ └─────────┘ └──────────┘ └──────────────┘
147
+ ```
148
+
149
+ More: [`docs/architecture.md`](./docs/architecture.md).
150
+
151
+ ## Contributing
152
+
153
+ See [CONTRIBUTING.md](./CONTRIBUTING.md). Short version: TypeScript strict, `npm run lint && npm run typecheck && npm test`, add a changeset, open a PR.
154
+
155
+ ## License
156
+
157
+ MIT © [Quantum Media Technologies sp. z o.o.](https://www.qmediat.io) — see [LICENSE](./LICENSE).
158
+
159
+ Part of qmediat's [open-source portfolio](https://www.qmediat.io/open-source).
@@ -0,0 +1,47 @@
1
+ /**
2
+ * Read/write the local credentials file used by Tier-2 auth.
3
+ *
4
+ * File: `~/.config/qmediat/credentials` (chmod 0600).
5
+ * Format: INI-like profile sections, compatible with AWS/Stripe conventions.
6
+ *
7
+ * [default]
8
+ * gemini_api_key = AIza...
9
+ * daily_budget_usd = 10.00
10
+ * default_model = latest-pro
11
+ *
12
+ * [work]
13
+ * gemini_api_key = AIza...
14
+ * default_model = latest-flash
15
+ */
16
+ export interface ProfileData {
17
+ geminiApiKey?: string;
18
+ defaultModel?: string;
19
+ dailyBudgetUsd?: number;
20
+ vertexProject?: string;
21
+ vertexLocation?: string;
22
+ }
23
+ type ProfilesMap = Map<string, ProfileData>;
24
+ /** Load all profiles from disk. Returns empty map if the file doesn't exist. */
25
+ export declare function loadCredentials(): ProfilesMap;
26
+ /** Load a single profile. Throws if missing. */
27
+ export declare function loadProfile(name: string): ProfileData;
28
+ /**
29
+ * Validate a profile name against injection vectors.
30
+ *
31
+ * INI section headers are `[name]` — if `name` contains `]`, `[`, `\n`, `\r`,
32
+ * or `=`, a malicious name could create phantom sections or confuse the parser.
33
+ * readline strips `\n` from interactive input, but a programmatic caller has no
34
+ * such protection; this whitelist is the authoritative defense.
35
+ */
36
+ export declare function sanitizeProfileName(name: string): string;
37
+ /**
38
+ * Persist a single profile, preserving other profiles.
39
+ *
40
+ * Writes atomically via `tmp + rename` so that a chmod / write failure never
41
+ * leaves the secret on disk with the wrong permissions. On POSIX, tmp is
42
+ * created with `O_EXCL` (`flag:'wx'`) to defeat symlink attacks between the
43
+ * existence check and the write.
44
+ */
45
+ export declare function saveProfile(name: string, data: ProfileData): void;
46
+ export {};
47
+ //# sourceMappingURL=credentials-store.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"credentials-store.d.ts","sourceRoot":"","sources":["../../src/auth/credentials-store.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAgBH,MAAM,WAAW,WAAW;IAC1B,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,cAAc,CAAC,EAAE,MAAM,CAAC;CACzB;AAED,KAAK,WAAW,GAAG,GAAG,CAAC,MAAM,EAAE,WAAW,CAAC,CAAC;AA6F5C,gFAAgF;AAChF,wBAAgB,eAAe,IAAI,WAAW,CAU7C;AAED,gDAAgD;AAChD,wBAAgB,WAAW,CAAC,IAAI,EAAE,MAAM,GAAG,WAAW,CASrD;AAED;;;;;;;GAOG;AACH,wBAAgB,mBAAmB,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAgBxD;AAED;;;;;;;GAOG;AACH,wBAAgB,WAAW,CAAC,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,WAAW,GAAG,IAAI,CAoDjE"}
@@ -0,0 +1,215 @@
1
+ /**
2
+ * Read/write the local credentials file used by Tier-2 auth.
3
+ *
4
+ * File: `~/.config/qmediat/credentials` (chmod 0600).
5
+ * Format: INI-like profile sections, compatible with AWS/Stripe conventions.
6
+ *
7
+ * [default]
8
+ * gemini_api_key = AIza...
9
+ * daily_budget_usd = 10.00
10
+ * default_model = latest-pro
11
+ *
12
+ * [work]
13
+ * gemini_api_key = AIza...
14
+ * default_model = latest-flash
15
+ */
16
+ import { randomBytes } from 'node:crypto';
17
+ import { chmodSync, existsSync, mkdirSync, readFileSync, renameSync, statSync, unlinkSync, writeFileSync, } from 'node:fs';
18
+ import { logger } from '../utils/logger.js';
19
+ import { credentialsPath, qmediatConfigDir } from '../utils/paths.js';
20
+ /** Parse INI-style credentials content. */
21
+ function parseIni(raw) {
22
+ const profiles = new Map();
23
+ let current = null;
24
+ for (const rawLine of raw.split('\n')) {
25
+ const line = rawLine.trim();
26
+ if (line.length === 0 || line.startsWith('#') || line.startsWith(';'))
27
+ continue;
28
+ const sectionMatch = /^\[([^\]]+)\]$/.exec(line);
29
+ if (sectionMatch && sectionMatch[1] !== undefined) {
30
+ current = sectionMatch[1].trim();
31
+ if (!profiles.has(current))
32
+ profiles.set(current, {});
33
+ continue;
34
+ }
35
+ if (current === null)
36
+ continue;
37
+ const kvMatch = /^([^=]+)=(.*)$/.exec(line);
38
+ if (!kvMatch || kvMatch[1] === undefined || kvMatch[2] === undefined)
39
+ continue;
40
+ const key = kvMatch[1].trim();
41
+ const value = kvMatch[2].trim();
42
+ const data = profiles.get(current);
43
+ switch (key) {
44
+ case 'gemini_api_key':
45
+ data.geminiApiKey = value;
46
+ break;
47
+ case 'default_model':
48
+ data.defaultModel = value;
49
+ break;
50
+ case 'daily_budget_usd': {
51
+ const n = Number.parseFloat(value);
52
+ if (Number.isFinite(n))
53
+ data.dailyBudgetUsd = n;
54
+ break;
55
+ }
56
+ case 'vertex_project':
57
+ data.vertexProject = value;
58
+ break;
59
+ case 'vertex_location':
60
+ data.vertexLocation = value;
61
+ break;
62
+ default:
63
+ break;
64
+ }
65
+ }
66
+ return profiles;
67
+ }
68
+ /** Serialize profiles back to INI format. */
69
+ function serializeIni(profiles) {
70
+ const chunks = [
71
+ '# qmediat credentials — keep this file private (chmod 0600)',
72
+ '# Do NOT commit to version control.',
73
+ '',
74
+ ];
75
+ for (const [name, data] of profiles) {
76
+ chunks.push(`[${name}]`);
77
+ if (data.geminiApiKey !== undefined)
78
+ chunks.push(`gemini_api_key = ${data.geminiApiKey}`);
79
+ if (data.defaultModel !== undefined)
80
+ chunks.push(`default_model = ${data.defaultModel}`);
81
+ if (data.dailyBudgetUsd !== undefined) {
82
+ chunks.push(`daily_budget_usd = ${data.dailyBudgetUsd.toFixed(2)}`);
83
+ }
84
+ if (data.vertexProject !== undefined)
85
+ chunks.push(`vertex_project = ${data.vertexProject}`);
86
+ if (data.vertexLocation !== undefined)
87
+ chunks.push(`vertex_location = ${data.vertexLocation}`);
88
+ chunks.push('');
89
+ }
90
+ return chunks.join('\n');
91
+ }
92
+ /**
93
+ * Warn if the credentials file has permissions broader than owner-only on POSIX.
94
+ * Windows NTFS ACLs can't be inspected via `mode`; we log a one-shot note there.
95
+ */
96
+ function warnOnLoosePermissions(path) {
97
+ if (process.platform === 'win32')
98
+ return;
99
+ try {
100
+ const mode = statSync(path).mode & 0o777;
101
+ if ((mode & 0o077) !== 0) {
102
+ logger.warn(`Credentials file ${path} has permissions 0${mode.toString(8).padStart(3, '0')} — group/other have access. Run 'chmod 0600 ${path}' to restrict.`);
103
+ }
104
+ }
105
+ catch {
106
+ /* best-effort */
107
+ }
108
+ }
109
+ /** Load all profiles from disk. Returns empty map if the file doesn't exist. */
110
+ export function loadCredentials() {
111
+ const path = credentialsPath();
112
+ if (!existsSync(path))
113
+ return new Map();
114
+ warnOnLoosePermissions(path);
115
+ try {
116
+ const raw = readFileSync(path, 'utf8');
117
+ return parseIni(raw);
118
+ }
119
+ catch {
120
+ return new Map();
121
+ }
122
+ }
123
+ /** Load a single profile. Throws if missing. */
124
+ export function loadProfile(name) {
125
+ const profiles = loadCredentials();
126
+ const profile = profiles.get(name);
127
+ if (!profile) {
128
+ throw new Error(`Credentials profile '${name}' not found in ${credentialsPath()}. Run \`npx @qmediat.io/gemini-code-context-mcp init\` to create it.`);
129
+ }
130
+ return profile;
131
+ }
132
+ /**
133
+ * Validate a profile name against injection vectors.
134
+ *
135
+ * INI section headers are `[name]` — if `name` contains `]`, `[`, `\n`, `\r`,
136
+ * or `=`, a malicious name could create phantom sections or confuse the parser.
137
+ * readline strips `\n` from interactive input, but a programmatic caller has no
138
+ * such protection; this whitelist is the authoritative defense.
139
+ */
140
+ export function sanitizeProfileName(name) {
141
+ // Block INI-syntax chars (`[`, `]`, `=`, `#`, `;`), whitespace-class chars
142
+ // that readline may pass through (`\n`, `\r`, `\t`), and ASCII control chars
143
+ // (`\x00`-`\x1f`). Unicode letters (accented, CJK, etc.) are allowed because
144
+ // profile names are stored locally and displayed back to their creator — no
145
+ // reason to restrict to ASCII.
146
+ if (name.length === 0 || name.length > 32) {
147
+ throw new Error(`Invalid profile name '${name}': must be 1-32 characters.`);
148
+ }
149
+ // biome-ignore lint/suspicious/noControlCharactersInRegex: rejecting control chars IS the intent here
150
+ if (/[[\]=#;\n\r\t]/.test(name) || /[\u0000-\u001f]/.test(name)) {
151
+ throw new Error(`Invalid profile name '${name}': must not contain INI syntax chars ('[', ']', '=', '#', ';') or whitespace/control chars.`);
152
+ }
153
+ return name;
154
+ }
155
+ /**
156
+ * Persist a single profile, preserving other profiles.
157
+ *
158
+ * Writes atomically via `tmp + rename` so that a chmod / write failure never
159
+ * leaves the secret on disk with the wrong permissions. On POSIX, tmp is
160
+ * created with `O_EXCL` (`flag:'wx'`) to defeat symlink attacks between the
161
+ * existence check and the write.
162
+ */
163
+ export function saveProfile(name, data) {
164
+ const safeName = sanitizeProfileName(name);
165
+ const dir = qmediatConfigDir();
166
+ // Create OR tighten the config directory BEFORE any write. `mkdirSync({mode})`
167
+ // only applies when creating — for an existing dir (possibly created by a
168
+ // previous tool at 0o755), we need an explicit chmod up front so the symlink
169
+ // window is as narrow as possible.
170
+ if (!existsSync(dir)) {
171
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
172
+ }
173
+ if (process.platform !== 'win32') {
174
+ try {
175
+ chmodSync(dir, 0o700);
176
+ }
177
+ catch {
178
+ /* best-effort — dir may be held by another process */
179
+ }
180
+ }
181
+ const path = credentialsPath();
182
+ const profiles = existsSync(path) ? loadCredentials() : new Map();
183
+ profiles.set(safeName, data);
184
+ const content = serializeIni(profiles);
185
+ // Random suffix (64 bits of entropy) defeats any attempt to predict the tmp
186
+ // name and pre-create a symlink at that path. `flag: 'wx'` then additionally
187
+ // fails if the path exists, so combined the attack surface is essentially nil.
188
+ const tmpPath = `${path}.tmp.${randomBytes(8).toString('hex')}`;
189
+ try {
190
+ // `flag: 'wx'` → O_CREAT | O_EXCL — fails if tmpPath exists, preventing
191
+ // symlink-attack overwrite of arbitrary targets.
192
+ writeFileSync(tmpPath, content, { mode: 0o600, flag: 'wx' });
193
+ if (process.platform !== 'win32') {
194
+ // Defensive: ensure perms even if umask altered the initial create mode.
195
+ chmodSync(tmpPath, 0o600);
196
+ }
197
+ else {
198
+ logger.warn(`Running on Windows — chmod(0600) has no effect on NTFS. The credentials file inherits ACLs from its parent directory. Verify access via: icacls "${path}"`);
199
+ }
200
+ // Atomic on same filesystem. After this line, the secret is at `path`
201
+ // with 0600 perms; there is no window where it exists with looser perms.
202
+ renameSync(tmpPath, path);
203
+ }
204
+ catch (err) {
205
+ try {
206
+ if (existsSync(tmpPath))
207
+ unlinkSync(tmpPath);
208
+ }
209
+ catch {
210
+ /* best-effort cleanup */
211
+ }
212
+ throw err;
213
+ }
214
+ }
215
+ //# sourceMappingURL=credentials-store.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"credentials-store.js","sourceRoot":"","sources":["../../src/auth/credentials-store.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAC1C,OAAO,EACL,SAAS,EACT,UAAU,EACV,SAAS,EACT,YAAY,EACZ,UAAU,EACV,QAAQ,EACR,UAAU,EACV,aAAa,GACd,MAAM,SAAS,CAAC;AACjB,OAAO,EAAE,MAAM,EAAE,MAAM,oBAAoB,CAAC;AAC5C,OAAO,EAAE,eAAe,EAAE,gBAAgB,EAAE,MAAM,mBAAmB,CAAC;AAYtE,2CAA2C;AAC3C,SAAS,QAAQ,CAAC,GAAW;IAC3B,MAAM,QAAQ,GAAgB,IAAI,GAAG,EAAE,CAAC;IACxC,IAAI,OAAO,GAAkB,IAAI,CAAC;IAElC,KAAK,MAAM,OAAO,IAAI,GAAG,CAAC,KAAK,CAAC,IAAI,CAAC,EAAE,CAAC;QACtC,MAAM,IAAI,GAAG,OAAO,CAAC,IAAI,EAAE,CAAC;QAC5B,IAAI,IAAI,CAAC,MAAM,KAAK,CAAC,IAAI,IAA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 10 chars return `***` to avoid leaking weak values.
6
+ */
7
+ export declare function fingerprint(apiKey: string | undefined | null): string;
8
+ //# sourceMappingURL=fingerprint.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"fingerprint.d.ts","sourceRoot":"","sources":["../../src/auth/fingerprint.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,wBAAgB,WAAW,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,GAAG,IAAI,GAAG,MAAM,CAGrE"}
@@ -0,0 +1,12 @@
1
+ /**
2
+ * Safe partial-key preview for logging and UI.
3
+ *
4
+ * Never logs the full API key. Format: `AIza...xyz9` (first 4 + last 4 chars).
5
+ * Keys shorter than 10 chars return `***` to avoid leaking weak values.
6
+ */
7
+ export function fingerprint(apiKey) {
8
+ if (!apiKey || apiKey.length < 10)
9
+ return '***';
10
+ return `${apiKey.slice(0, 4)}...${apiKey.slice(-4)}`;
11
+ }
12
+ //# sourceMappingURL=fingerprint.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"fingerprint.js","sourceRoot":"","sources":["../../src/auth/fingerprint.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,MAAM,UAAU,WAAW,CAAC,MAAiC;IAC3D,IAAI,CAAC,MAAM,IAAI,MAAM,CAAC,MAAM,GAAG,EAAE;QAAE,OAAO,KAAK,CAAC;IAChD,OAAO,GAAG,MAAM,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,MAAM,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;AACvD,CAAC"}
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Interactive `init` subcommand — guides the user through secure credential setup.
3
+ *
4
+ * Writes `~/.config/qmediat/credentials` with chmod 0600. Offers to print an MCP
5
+ * host config snippet to paste into `~/.claude.json` (etc.) that references the
6
+ * profile by name rather than embedding the key.
7
+ */
8
+ export declare function runInit(): Promise<void>;
9
+ //# sourceMappingURL=init-command.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"init-command.d.ts","sourceRoot":"","sources":["../../src/auth/init-command.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAkLH,wBAAsB,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC,CA0G7C"}