yats-toolkit 0.6.4 → 0.8.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.
@@ -1,10 +1,9 @@
1
1
  {
2
- "servers": [
3
- {
4
- "name": "yats",
5
- "type": "local",
2
+ "mcpServers": {
3
+ "yats": {
4
+ "type": "stdio",
6
5
  "command": "yats",
7
6
  "args": ["bridge"]
8
7
  }
9
- ]
8
+ }
10
9
  }
@@ -0,0 +1,9 @@
1
+ {
2
+ "servers": {
3
+ "yats": {
4
+ "type": "stdio",
5
+ "command": "yats",
6
+ "args": ["bridge"]
7
+ }
8
+ }
9
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "yats-toolkit",
3
- "version": "0.6.4",
3
+ "version": "0.8.0",
4
4
  "description": "YATS — Yet Another Token Saver. One-command MCP server that indexes your codebase into a knowledge graph so AI agents (Claude, Cursor, Copilot) can search and navigate it without burning tokens.",
5
5
  "author": "Franco Vinciarelli <vinciarellifranco@gmail.com>",
6
6
  "license": "SEE LICENSE IN LICENSE",
@@ -52,6 +52,9 @@
52
52
  "test": "node --test --test-concurrency=1 src/*.test.js"
53
53
  },
54
54
  "dependencies": {},
55
+ "devDependencies": {
56
+ "yaml": "^2.7.0"
57
+ },
55
58
  "engines": {
56
59
  "node": ">=18.0.0"
57
60
  }
package/src/connect.js CHANGED
@@ -15,6 +15,7 @@
15
15
  */
16
16
  import { writeFileSync, readFileSync, existsSync, mkdirSync } from "node:fs";
17
17
  import { join, dirname } from "node:path";
18
+ import { fileURLToPath } from "node:url";
18
19
  import { createInterface } from "node:readline";
19
20
  import { homedir } from "node:os";
20
21
  import { spawnSync } from "node:child_process";
@@ -54,10 +55,21 @@ const AGENTS = {
54
55
  transport: "stdio bridge",
55
56
  files: [
56
57
  { src: "connect/copilot/instructions.md", dest: ".github/copilot-instructions.md", type: "text" },
57
- { src: "connect/copilot/mcp.json", dest: ".copilot/mcp.json", type: "json" },
58
+ // VS Code Chat / Copilot Agent Host reads the portable .mcp.json at the
59
+ // repo root (mcpServers format), not .copilot/mcp.json (CLI-only format).
60
+ { src: "connect/copilot/mcp.json", dest: ".mcp.json", type: "json" },
58
61
  ],
59
62
  url: "https://github.com/fvinciarelli/yats.ai/tree/main/connect/copilot",
60
63
  },
64
+ vscode: {
65
+ name: "VS Code (native MCP)",
66
+ transport: "stdio bridge",
67
+ files: [
68
+ // Native VS Code workspace MCP config (servers format).
69
+ { src: "connect/vscode/mcp.json", dest: ".vscode/mcp.json", type: "json" },
70
+ ],
71
+ url: "https://github.com/fvinciarelli/yats.ai/tree/main/connect/vscode",
72
+ },
61
73
  gemini: {
62
74
  name: "Gemini CLI",
63
75
  transport: "stdio bridge",
@@ -79,17 +91,23 @@ const AGENTS = {
79
91
  };
80
92
 
81
93
  function getYatsMcpConfig() {
94
+ let cfg = { mcpServers: { yats: { url: "http://localhost:5555/mcp" } } };
82
95
  try {
83
- return JSON.parse(readFileSync(MCP_CONFIG_FILE, "utf-8"));
84
- } catch {
85
- return { mcpServers: { yats: { url: "http://localhost:5555/mcp/sse" } } };
96
+ cfg = JSON.parse(readFileSync(MCP_CONFIG_FILE, "utf-8"));
97
+ } catch { /* no config yet — use the default above */ }
98
+ // Normalize legacy /mcp/sse URLs to the Streamable HTTP endpoint.
99
+ const url = cfg?.mcpServers?.yats?.url;
100
+ if (typeof url === "string" && url.endsWith("/mcp/sse")) {
101
+ cfg.mcpServers.yats.url = url.slice(0, -4);
86
102
  }
103
+ return cfg;
87
104
  }
88
105
 
89
106
  function getFileContent(srcPath) {
90
- // Templates ship inside the package (connect/ dir) — resolves from src/ → ../connect/
107
+ // Templates ship inside the package (connect/ dir) — resolves from src/ → ../connect/.
108
+ // fileURLToPath handles percent-encoded paths (spaces, unicode) and Windows drives.
91
109
  try {
92
- const pkgDir = dirname(new URL(import.meta.url).pathname);
110
+ const pkgDir = dirname(fileURLToPath(import.meta.url));
93
111
  const installedPath = join(pkgDir, "..", srcPath);
94
112
  if (existsSync(installedPath)) {
95
113
  return readFileSync(installedPath, "utf-8");
@@ -102,7 +120,7 @@ function getFileContent(srcPath) {
102
120
  // Render / template helpers
103
121
  // ============================================================
104
122
 
105
- function renderContent(srcPath) {
123
+ export function renderContent(srcPath) {
106
124
  const content = getFileContent(srcPath);
107
125
  if (content === null) {
108
126
  console.log(` ${RED}✗${R} Missing template ${srcPath} — reinstall yats-toolkit`);
@@ -135,14 +153,84 @@ function appendMarker(agentKey) {
135
153
  // Install helpers
136
154
  // ============================================================
137
155
 
138
- function safeMergeJson(existingPath, newEntry) {
139
- let obj = {};
156
+ /** Read an existing JSON config as an object, or null if missing/invalid. */
157
+ function readJsonObject(path) {
140
158
  try {
141
- obj = JSON.parse(readFileSync(existingPath, "utf-8"));
142
- } catch { /* file doesn't exist or invalid, start fresh */ }
143
- if (!obj.mcpServers) obj.mcpServers = {};
144
- obj.mcpServers = { ...obj.mcpServers, ...newEntry.mcpServers };
145
- return JSON.stringify(obj, null, 2) + "\n";
159
+ const obj = JSON.parse(readFileSync(path, "utf-8"));
160
+ return obj && typeof obj === "object" && !Array.isArray(obj) ? obj : null;
161
+ } catch {
162
+ return null;
163
+ }
164
+ }
165
+
166
+ /**
167
+ * Merge an agent template into an existing JSON config. Templates carry one
168
+ * of two shapes — `mcpServers` (Claude/Copilot/Gemini/Cursor) or `servers`
169
+ * (VS Code native) — both objects keyed by server name. Existing entries are
170
+ * preserved; only the YATS entry is added or updated.
171
+ */
172
+ export function mergeServerConfig(existing, template) {
173
+ const out = {};
174
+ for (const key of Object.keys(existing)) out[key] = existing[key];
175
+ for (const key of Object.keys(template)) {
176
+ const tpl = template[key];
177
+ if (tpl && typeof tpl === "object" && !Array.isArray(tpl)) {
178
+ const base =
179
+ out[key] && typeof out[key] === "object" && !Array.isArray(out[key])
180
+ ? out[key]
181
+ : {};
182
+ out[key] = { ...base, ...tpl };
183
+ } else {
184
+ out[key] = tpl;
185
+ }
186
+ }
187
+ return out;
188
+ }
189
+
190
+ /**
191
+ * Install one agent's JSON config file from its template.
192
+ * The template is the source of truth (correct format + transport per
193
+ * agent: stdio bridge for copilot/claude/gemini/vscode, HTTP for cursor) —
194
+ * never the global ~/.yats/mcp-config.json, which is HTTP-only and generic.
195
+ * Non-destructive: existing files are merged, other entries preserved.
196
+ */
197
+ function installJsonFile(file) {
198
+ const templateContent = renderContent(file.src);
199
+ if (templateContent === null) {
200
+ console.log(` ${RED}✗${R} Missing template ${file.src} — reinstall yats-toolkit`);
201
+ return false;
202
+ }
203
+
204
+ let templateObj;
205
+ try {
206
+ templateObj = JSON.parse(templateContent);
207
+ } catch {
208
+ console.log(` ${RED}✗${R} Invalid template ${file.src}`);
209
+ return false;
210
+ }
211
+
212
+ const destPath = file.dest;
213
+ const exists = existsSync(destPath);
214
+ let merged = templateObj;
215
+ if (exists) {
216
+ const existing = readJsonObject(destPath);
217
+ if (existing === null) {
218
+ console.log(` ${Y}⚠${R} ${destPath} exists but is not valid JSON — left untouched.`);
219
+ return false;
220
+ }
221
+ merged = mergeServerConfig(existing, templateObj);
222
+ }
223
+
224
+ mkdirSync(dirname(destPath), { recursive: true });
225
+ writeFileSync(destPath, JSON.stringify(merged, null, 2) + "\n");
226
+ if (exists) {
227
+ console.log(` ${Y}↻${R} Merged YATS into existing ${destPath}`);
228
+ console.log(` ${D} Added/updated: ${JSON.stringify(templateObj)}${R}`);
229
+ console.log(` ${D} Your existing entries are preserved.${R}`);
230
+ } else {
231
+ console.log(` ${G}✓${R} Created ${destPath}`);
232
+ }
233
+ return true;
146
234
  }
147
235
 
148
236
  // Single shared readline so piped stdin keeps working across multiple prompts
@@ -225,22 +313,10 @@ async function installFiles(agentKey, prompter) {
225
313
 
226
314
  for (const file of agent.files) {
227
315
  const destPath = file.dest;
228
- const mcpConfig = getYatsMcpConfig();
229
316
 
230
317
  if (file.type === "json") {
231
- const exists = existsSync(destPath);
232
- const merged = safeMergeJson(destPath, mcpConfig);
233
- mkdirSync(dirname(destPath), { recursive: true });
234
- writeFileSync(destPath, merged);
235
- if (exists) {
236
- console.log(` ${Y}↻${R} Merged YATS into existing ${destPath}`);
237
- const entry = mcpConfig.mcpServers.yats;
238
- console.log(` ${D} Added: mcpServers.yats → ${JSON.stringify(entry)}${R}`);
239
- console.log(` ${D} Your existing entries are preserved.${R}`);
240
- } else {
241
- console.log(` ${G}✓${R} Created ${destPath}`);
242
- }
243
- installed++;
318
+ if (installJsonFile(file)) installed++;
319
+ else skipped++;
244
320
  } else if (file.type === "toml") {
245
321
  const exists = existsSync(destPath);
246
322
  mkdirSync(dirname(destPath), { recursive: true });
@@ -301,6 +377,15 @@ async function installFiles(agentKey, prompter) {
301
377
  console.log(` Done: ${installed} installed, ${skipped} skipped.`);
302
378
  console.log(` Full instructions: ${C}${agent.url}${R}`);
303
379
  console.log("");
380
+
381
+ // Copilot switched from .copilot/mcp.json (CLI format) to the portable
382
+ // .mcp.json at the repo root (Agent Host format). Point out the legacy file
383
+ // so the old config doesn't linger unnoticed.
384
+ if (agentKey === "copilot" && existsSync(".copilot/mcp.json")) {
385
+ console.log(` ${Y}⚠${R} Legacy .copilot/mcp.json found — Copilot now reads .mcp.json (Agent Host format).`);
386
+ console.log(` ${D} Remove the old file if unused.${R}`);
387
+ console.log("");
388
+ }
304
389
  }
305
390
 
306
391
  // ============================================================
@@ -365,8 +450,6 @@ function showConfig(agentKey) {
365
450
  process.exit(1);
366
451
  }
367
452
 
368
- const mcpConfig = getYatsMcpConfig();
369
-
370
453
  console.log("");
371
454
  console.log(` ${B}${agent.name}${R} — via ${agent.transport}`);
372
455
  console.log("");
@@ -374,7 +457,19 @@ function showConfig(agentKey) {
374
457
  for (const file of agent.files) {
375
458
  console.log(` ${B}${file.dest}${R}`);
376
459
  if (file.type === "json") {
377
- console.log(` ${D}${safeMergeJson("", mcpConfig).replace(/\n/g, "\n ")}${R}`);
460
+ const templateContent = renderContent(file.src);
461
+ if (templateContent) {
462
+ try {
463
+ const tpl = JSON.parse(templateContent);
464
+ const existing = existsSync(file.dest) ? readJsonObject(file.dest) : null;
465
+ const preview = existing ? mergeServerConfig(existing, tpl) : tpl;
466
+ console.log(` ${D}${JSON.stringify(preview, null, 2).replace(/\n/g, "\n ")}${R}`);
467
+ } catch {
468
+ console.log(` ${D}${templateContent.replace(/\n/g, "\n ")}${R}`);
469
+ }
470
+ } else {
471
+ console.log(` ${RED}(missing template)${R}`);
472
+ }
378
473
  } else {
379
474
  const content = renderContent(file.src);
380
475
  if (content) {
@@ -465,6 +560,7 @@ export default async function connect(args) {
465
560
  { label: "Claude Code", value: "claude" },
466
561
  { label: "Cursor", value: "cursor" },
467
562
  { label: "GitHub Copilot", value: "copilot" },
563
+ { label: "VS Code (native MCP)", value: "vscode" },
468
564
  { label: "Gemini CLI", value: "gemini" },
469
565
  { label: "Codex CLI", value: "codex" },
470
566
  ]);
@@ -0,0 +1,86 @@
1
+ /**
2
+ * Tests — yats connect: template-based JSON install + non-destructive merge.
3
+ *
4
+ * Covers the regression that shipped wrong MCP configs: the JSON install
5
+ * branch ignored the agent templates and wrote the generic HTTP config from
6
+ * ~/.yats/mcp-config.json (legacy /mcp/sse URL, mcpServers format) — Copilot
7
+ * got that instead of its stdio-bridge template.
8
+ */
9
+
10
+ import { describe, it } from "node:test";
11
+ import assert from "node:assert/strict";
12
+
13
+ import { mergeServerConfig, renderContent } from "./connect.js";
14
+
15
+ describe("mergeServerConfig", () => {
16
+ it("merges mcpServers entries, preserving existing servers", () => {
17
+ const existing = {
18
+ mcpServers: {
19
+ github: { command: "npx", args: ["@github/mcp"] },
20
+ yats: { url: "http://localhost:5555/mcp/sse" },
21
+ },
22
+ };
23
+ const template = {
24
+ mcpServers: { yats: { type: "stdio", command: "yats", args: ["bridge"] } },
25
+ };
26
+ const merged = mergeServerConfig(existing, template);
27
+ assert.deepEqual(merged.mcpServers.github, existing.mcpServers.github);
28
+ assert.deepEqual(merged.mcpServers.yats, {
29
+ type: "stdio",
30
+ command: "yats",
31
+ args: ["bridge"],
32
+ });
33
+ });
34
+
35
+ it("merges VS Code native `servers` objects by name", () => {
36
+ const existing = {
37
+ servers: { other: { type: "http", url: "https://example.com/mcp" } },
38
+ };
39
+ const template = {
40
+ servers: { yats: { type: "stdio", command: "yats", args: ["bridge"] } },
41
+ };
42
+ const merged = mergeServerConfig(existing, template);
43
+ assert.deepEqual(merged.servers.other, existing.servers.other);
44
+ assert.deepEqual(merged.servers.yats, template.servers.yats);
45
+ });
46
+
47
+ it("keeps non-object keys from both sides", () => {
48
+ const merged = mergeServerConfig(
49
+ { comment: "mine" },
50
+ { note: "template" },
51
+ );
52
+ assert.equal(merged.comment, "mine");
53
+ assert.equal(merged.note, "template");
54
+ });
55
+ });
56
+
57
+ describe("agent templates (shipped in the package)", () => {
58
+ it("copilot template targets .mcp.json with the stdio bridge (mcpServers)", () => {
59
+ const content = renderContent("connect/copilot/mcp.json");
60
+ assert.ok(content, "template must resolve from the package");
61
+ const tpl = JSON.parse(content);
62
+ assert.deepEqual(tpl, {
63
+ mcpServers: {
64
+ yats: { type: "stdio", command: "yats", args: ["bridge"] },
65
+ },
66
+ });
67
+ });
68
+
69
+ it("vscode template uses the native `servers` format with the bridge", () => {
70
+ const content = renderContent("connect/vscode/mcp.json");
71
+ assert.ok(content, "vscode template must resolve");
72
+ const tpl = JSON.parse(content);
73
+ assert.equal(tpl.servers.yats.type, "stdio");
74
+ assert.equal(tpl.servers.yats.command, "yats");
75
+ assert.deepEqual(tpl.servers.yats.args, ["bridge"]);
76
+ });
77
+
78
+ it("text templates resolve and replace __REPO_PATH__", () => {
79
+ const content = renderContent("connect/copilot/instructions.md");
80
+ assert.ok(content, "instructions template must resolve");
81
+ assert.ok(!content.includes("__REPO_PATH__"));
82
+ // The replacement is the caller's working directory — must never be
83
+ // hardcoded (CI runs from a different path).
84
+ assert.ok(content.includes(`yats index ${process.cwd()}`));
85
+ });
86
+ });
package/src/setup.js CHANGED
@@ -37,9 +37,6 @@ const DEFAULT_DOC_EXTENSIONS = ".md,.mdx,.rst,.txt,.adoc,.org,.wiki,.readme";
37
37
  const DEFAULT_SKIP_EXTENSIONS = ".exe,.dll,.so,.o,.a,.bin,.zip,.tar,.gz,.bz2,.xz,.7z,.rar,.png,.jpg,.jpeg,.gif,.ico,.webp,.bmp,.svg,.woff,.woff2,.ttf,.eot,.otf,.mp3,.mp4,.avi,.mov,.mkv,.flv,.wmv,.webm,.pdf,.doc,.docx,.xls,.xlsx,.ppt,.pptx,.lock,.log,.map,.min.js,.min.css";
38
38
  const DEFAULT_IGNORED_DIRS = "node_modules,.git,dist,build,.next,__pycache__,vendor,target,bin,obj,.venv,venv,.yarn,.pnpm";
39
39
 
40
- const GITHUB_COMPOSE_URL =
41
- "https://raw.githubusercontent.com/fvinciarelli/yats.ai/main/docker/docker-compose.yml";
42
-
43
40
  const B = "\x1b[1m";
44
41
  const D = "\x1b[2m";
45
42
  const R = "\x1b[0m";
@@ -80,7 +77,11 @@ const PROVIDER_MODELS = {
80
77
 
81
78
  const DEFAULT_MODEL = { openai: "text-embedding-3-small", azure: "text-embedding-3-small", mistral: "mistral-embed", voyage: "voyage-code-2", ollama: "nomic-embed-text" };
82
79
 
83
- // Minimal embedded docker-compose as fallback
80
+ // Default Ollama URL when the bundled container is used. External Ollama
81
+ // deployments (host or remote) set OLLAMA_URL in ~/.yats/.env instead.
82
+ const DEFAULT_OLLAMA_URL = "http://ollama:11434";
83
+
84
+ // Embedded docker-compose template (this is what `yats setup` installs)
84
85
  const EMBEDDED_COMPOSE = `services:
85
86
  neo4j:
86
87
  image: neo4j:5.26-community
@@ -118,17 +119,19 @@ const EMBEDDED_COMPOSE = `services:
118
119
  retries: 5
119
120
  start_period: 5s
120
121
  restart: unless-stopped
121
- __OLLAMA_PLACEHOLDER__
122
+ __OLLAMA_PLACEHOLDER__
122
123
  yats:
123
124
  image: ghcr.io/fvinciarelli/yats.ai:latest
124
125
  ports: ["__MCP_PORT__:__MCP_PORT__"]
126
+ extra_hosts:
127
+ - "host.docker.internal:host-gateway"
125
128
  environment:
126
129
  - NEO4J_URI=bolt://neo4j:7687
127
130
  - NEO4J_USER=neo4j
128
131
  - NEO4J_PASSWORD=\${NEO4J_PASSWORD:-password}
129
132
  - QDRANT_URL=http://qdrant:6333
130
133
  - EMBEDDING_PROVIDER=\${EMBEDDING_PROVIDER:-ollama}
131
- - OLLAMA_URL=http://ollama:11434
134
+ - OLLAMA_URL=\${OLLAMA_URL:-http://ollama:11434}
132
135
  - OLLAMA_MODEL=\${EMBEDDING_OLLAMA_MODEL:-nomic-embed-text}
133
136
  - OPENAI_API_KEY=\${EMBEDDING_OPENAI_API_KEY:-}
134
137
  - OPENAI_MODEL=\${EMBEDDING_OPENAI_MODEL:-text-embedding-3-small}
@@ -165,6 +168,7 @@ volumes:
165
168
  neo4j-data:
166
169
  neo4j-logs:
167
170
  qdrant-storage:
171
+ __OLLAMA_VOLUME__
168
172
  `;
169
173
 
170
174
  const OLLAMA_SERVICE = ` ollama:
@@ -182,7 +186,6 @@ const OLLAMA_SERVICE = ` ollama:
182
186
  sleep 5
183
187
  ollama pull \${EMBEDDING_OLLAMA_MODEL:-nomic-embed-text} 2>/dev/null || true
184
188
  wait
185
- ollama-models:
186
189
  `;
187
190
 
188
191
  // ============================================================
@@ -369,17 +372,48 @@ async function checkYatsRunning() {
369
372
  });
370
373
  }
371
374
 
375
+ async function checkOllama() {
376
+ // Is an Ollama server already answering on this machine (native app,
377
+ // systemd service, or the client's own container with a published port)?
378
+ try {
379
+ const res = await fetch("http://localhost:11434/api/tags", {
380
+ signal: AbortSignal.timeout(2000),
381
+ });
382
+ return res.ok;
383
+ } catch {
384
+ return false;
385
+ }
386
+ }
387
+
388
+ // From inside the YATS container, "localhost" is the container itself, so
389
+ // rewrite host-local URLs to the Docker host gateway.
390
+ function normalizeOllamaUrl(url) {
391
+ return url.replace(/^(https?):\/\/(localhost|127\.0\.0\.1|\[::1\])(:\d+)?/i, "http://host.docker.internal$3");
392
+ }
393
+
372
394
  // ============================================================
373
395
  // Compose file generation
374
396
  // ============================================================
375
397
 
376
- function generateCompose(provider, mcpPort, batchSize, indexDocs, docMaxFiles) {
398
+ // Generate ~/.yats/docker-compose.yml from the embedded template.
399
+ //
400
+ // Placeholder indentation matters: __OLLAMA_PLACEHOLDER__ sits at column 0
401
+ // because OLLAMA_SERVICE carries its own indentation, and __OLLAMA_VOLUME__
402
+ // sits inside the top-level volumes: section. Do not "align" them.
403
+ export function generateCompose(provider, mcpPort, batchSize, indexDocs, docMaxFiles, ollamaUrl = "") {
377
404
  let compose = EMBEDDED_COMPOSE;
378
405
 
379
- if (provider === "ollama") {
380
- compose = compose.replace("__OLLAMA_PLACEHOLDER__", OLLAMA_SERVICE);
406
+ // The bundled Ollama container is used only when no external Ollama was
407
+ // chosen (the in-container default URL counts as "bundled").
408
+ const useOllamaContainer = provider === "ollama" && (!ollamaUrl || ollamaUrl === DEFAULT_OLLAMA_URL);
409
+ if (useOllamaContainer) {
410
+ compose = compose
411
+ .replace("__OLLAMA_PLACEHOLDER__", OLLAMA_SERVICE)
412
+ .replace("__OLLAMA_VOLUME__", " ollama-models:");
381
413
  } else {
382
- compose = compose.replace("__OLLAMA_PLACEHOLDER__", "");
414
+ compose = compose
415
+ .replace("__OLLAMA_PLACEHOLDER__", "")
416
+ .replace("__OLLAMA_VOLUME__", "");
383
417
  }
384
418
 
385
419
  compose = compose
@@ -449,7 +483,7 @@ async function loadEnv() {
449
483
  // api key → EMBEDDING_<PROVIDER>_API_KEY
450
484
  // model → EMBEDDING_<PROVIDER>_MODEL (Azure: deployment name)
451
485
  // url → EMBEDDING_<PROVIDER>_BASE_URL / EMBEDDING_AZURE_ENDPOINT
452
- export function applyEnvKeys(envMap, { provider, apiKey, model, baseUrl, apiVersion }) {
486
+ export function applyEnvKeys(envMap, { provider, apiKey, model, baseUrl, apiVersion, ollamaUrl }) {
453
487
  envMap.EMBEDDING_PROVIDER = provider;
454
488
  envMap.YATS_PROVIDER = provider;
455
489
  if (provider === "openai" && apiKey) envMap.EMBEDDING_OPENAI_API_KEY = apiKey;
@@ -470,6 +504,12 @@ export function applyEnvKeys(envMap, { provider, apiKey, model, baseUrl, apiVers
470
504
  }
471
505
  const modelVar = { openai: "EMBEDDING_OPENAI_MODEL", azure: "EMBEDDING_AZURE_MODEL", mistral: "EMBEDDING_MISTRAL_MODEL", voyage: "EMBEDDING_VOYAGE_MODEL", ollama: "EMBEDDING_OLLAMA_MODEL" }[provider];
472
506
  if (model && modelVar) envMap[modelVar] = model;
507
+ if (provider === "ollama") {
508
+ // Container mode uses the default URL baked into docker-compose; only
509
+ // persist a URL when an external Ollama was chosen.
510
+ if (ollamaUrl && ollamaUrl !== DEFAULT_OLLAMA_URL) envMap.OLLAMA_URL = ollamaUrl;
511
+ else delete envMap.OLLAMA_URL;
512
+ }
473
513
  for (const k of ["ANTHROPIC_API_KEY", "OPENAI_API_KEY", "GEMINI_API_KEY", "DEEPSEEK_API_KEY"]) {
474
514
  if (!(k in envMap)) envMap[k] = "";
475
515
  }
@@ -479,6 +519,14 @@ export function applyEnvKeys(envMap, { provider, apiKey, model, baseUrl, apiVers
479
519
  return envMap;
480
520
  }
481
521
 
522
+ // PowerShell one-liner that appends <binDir> to the USER Path registry value:
523
+ // no 1024-char truncation (setx), no literal "%PATH%" (spawn passes args
524
+ // without shell expansion), keeps REG_EXPAND_SZ, and skips when already set.
525
+ export function windowsPathPowerShell(binDir) {
526
+ const p = binDir.replace(/'/g, "''");
527
+ return `$p=[string][Environment]::GetEnvironmentVariable('Path','User'); if (-not $p.Contains('${p}')) { [Microsoft.Win32.Registry]::SetValue('HKEY_CURRENT_USER\\Environment','Path', ($p.TrimEnd(';') + ';' + '${p}'), 'ExpandString') }`;
528
+ }
529
+
482
530
  // Verify a provider's connection before writing anything.
483
531
  // - openai/mistral/voyage: Bearer auth against {baseUrl}/embeddings, where
484
532
  // baseUrl is the provider default or a user-supplied custom endpoint.
@@ -543,6 +591,7 @@ async function main(options = {}) {
543
591
  batch: options.batch ? parseInt(options.batch, 10) : null,
544
592
  noDocs: options.noDocs || false,
545
593
  skipConfirm: options.skipConfirm || false,
594
+ ollamaUrl: options.ollamaUrl || env.OLLAMA_URL || null,
546
595
  };
547
596
 
548
597
  header();
@@ -618,6 +667,41 @@ async function main(options = {}) {
618
667
  ]);
619
668
  }
620
669
 
670
+ // Ollama: bundled container vs. an existing installation
671
+ let ollamaUrl = "";
672
+ if (provider === "ollama") {
673
+ if (nonInteractive) {
674
+ ollamaUrl = prefill.ollamaUrl || "";
675
+ if (ollamaUrl) ollamaUrl = normalizeOllamaUrl(ollamaUrl);
676
+ console.log(` Ollama: ${ollamaUrl && ollamaUrl !== DEFAULT_OLLAMA_URL ? ollamaUrl : "bundled Docker container"}`);
677
+ } else {
678
+ const hasOllama = await checkOllama();
679
+ step("Step 2 — Ollama");
680
+ const ollamaOptions = [];
681
+ if (hasOllama) {
682
+ ollamaOptions.push({ label: "Use my existing Ollama (detected on this machine)", value: "host" });
683
+ }
684
+ ollamaOptions.push({ label: "Run Ollama in Docker (bundled, ~3GB download)", value: "container" });
685
+ ollamaOptions.push({ label: "Use an existing Ollama at a custom URL", value: "custom" });
686
+ const ollamaMode = await choose("How should YATS connect to Ollama?", ollamaOptions);
687
+ if (ollamaMode === "host") {
688
+ ollamaUrl = "http://host.docker.internal:11434";
689
+ console.log(` ${G}✓${R} Using the Ollama already running on this machine.`);
690
+ } else if (ollamaMode === "custom") {
691
+ const rlUrl = createInterface({ input: process.stdin, output: process.stdout });
692
+ const answer = await ask(rlUrl, ` ${B}Ollama URL (e.g. http://192.168.1.20:11434):${R} `);
693
+ rlUrl.close();
694
+ ollamaUrl = normalizeOllamaUrl(answer.trim());
695
+ if (!ollamaUrl) {
696
+ console.log(` ${Y}⚠${R} No URL given — falling back to the bundled Ollama container.`);
697
+ } else {
698
+ console.log(` ${G}✓${R} Using Ollama at ${ollamaUrl}`);
699
+ }
700
+ }
701
+ console.log("");
702
+ }
703
+ }
704
+
621
705
  const providerNames = { openai: "OpenAI", azure: "Azure OpenAI", mistral: "Mistral", voyage: "Voyage AI" };
622
706
  let apiKey = "";
623
707
  let baseUrl = "";
@@ -742,7 +826,7 @@ async function main(options = {}) {
742
826
  if (nonInteractive) {
743
827
  console.log(` Embedding model: ${model}`);
744
828
  } else {
745
- step(provider === "ollama" ? "Step 2 — Embedding model" : "Step 3 — Embedding model");
829
+ step("Step 3 — Embedding model");
746
830
  model = await choose("Which embedding model?", PROVIDER_MODELS[provider]);
747
831
  console.log("");
748
832
  }
@@ -750,6 +834,20 @@ async function main(options = {}) {
750
834
  console.log(` Azure deployment: ${model}`);
751
835
  }
752
836
 
837
+ // Existing-host Ollama: best-effort pull of the chosen model so indexing
838
+ // works right away (skipped when Ollama lives elsewhere).
839
+ if (provider === "ollama" && ollamaUrl === "http://host.docker.internal:11434" && !nonInteractive) {
840
+ const sPull = spinner(`Pulling ${model} into your existing Ollama...`);
841
+ try {
842
+ await runCmd("ollama", ["pull", model]);
843
+ sPull.done(true);
844
+ } catch {
845
+ sPull.done(false);
846
+ console.log(` ${Y}⚠${R} Could not run 'ollama pull'. Make sure ${B}${model}${R} is available in your Ollama (e.g. docker exec <container> ollama pull ${model}).`);
847
+ }
848
+ console.log("");
849
+ }
850
+
753
851
  // Step 4: Embedding batch size
754
852
  const BATCH_DEFAULTS = { openai: 200, azure: 200, mistral: 200, voyage: 100, ollama: 4 };
755
853
  const BATCH_MAX = { openai: 2048, azure: 2048, mistral: 1024, voyage: 128, ollama: 4 };
@@ -805,7 +903,7 @@ async function main(options = {}) {
805
903
  // Optional: pre-index directories
806
904
  const pathsToIndex = [];
807
905
  if (!nonInteractive) {
808
- step("Step 5 — Pre-index (optional)");
906
+ step("Step 6 — Pre-index (optional)");
809
907
  console.log(` ${D}Indexing happens automatically on first search.${R}`);
810
908
  console.log(` ${D}Want to pre-index some directories now to skip the wait later?${R}`);
811
909
  console.log("");
@@ -851,18 +949,19 @@ async function main(options = {}) {
851
949
  mcpPort = suggested;
852
950
  }
853
951
  rlPort.close();
854
- console.log(` ${G}✓${R} MCP server on ${C}http://localhost:${mcpPort}/mcp/sse${R}`);
952
+ console.log(` ${G}✓${R} MCP server on ${C}http://localhost:${mcpPort}/mcp${R}`);
855
953
  console.log("");
856
954
  }
857
955
 
858
956
  // Confirm
859
957
  if (!nonInteractive && !prefill.skipConfirm) {
860
- step(`Step ${pathsToIndex.length ? "6" : "5"} — Confirm`);
958
+ step(`Step ${pathsToIndex.length ? "7" : "6"} — Confirm`);
861
959
  const providerName = provider === "ollama" || provider === "azure"
862
960
  ? `${provider === "ollama" ? "Ollama" : providerNames[provider]} (${model})`
863
961
  : providerNames[provider];
864
962
  box([
865
963
  `${B}Provider:${R} ${providerName}`,
964
+ ...(ollamaUrl && ollamaUrl !== DEFAULT_OLLAMA_URL ? [`${B}Ollama:${R} ${ollamaUrl}`] : []),
866
965
  ...(baseUrl ? [`${B}Endpoint:${R} ${baseUrl}`] : []),
867
966
  `${B}Port:${R} ${String(mcpPort)}`,
868
967
  ...(pathsToIndex.length ? [`${B}Pre-index:${R} ${String(pathsToIndex.length + " directorie(s)")}`] : []),
@@ -893,16 +992,16 @@ async function main(options = {}) {
893
992
  mkdirSync(REPOS_DIR, { recursive: true });
894
993
 
895
994
  // Generate and write docker-compose
896
- const compose = generateCompose(provider, mcpPort, batchSize, indexDocs, docMaxFiles);
995
+ const compose = generateCompose(provider, mcpPort, batchSize, indexDocs, docMaxFiles, ollamaUrl);
897
996
  writeFileSync(COMPOSE_FILE, compose);
898
997
 
899
998
  // Write MCP config
900
- const mcpConfig = { mcpServers: { yats: { url: `http://localhost:${mcpPort}/mcp/sse` } } };
999
+ const mcpConfig = { mcpServers: { yats: { url: `http://localhost:${mcpPort}/mcp` } } };
901
1000
  writeFileSync(MCP_CONFIG_FILE, JSON.stringify(mcpConfig, null, 2));
902
1001
 
903
1002
  // Persist keys to ~/.yats/.env — canonical source (embedding + benchmark keys).
904
1003
  const envMap = loadEnv();
905
- applyEnvKeys(envMap, { provider, apiKey, model, baseUrl, apiVersion });
1004
+ applyEnvKeys(envMap, { provider, apiKey, model, baseUrl, apiVersion, ollamaUrl });
906
1005
  writeFileSync(ENV_FILE, Object.entries(envMap).map(([k, v]) => `${k}=${v}`).join("\n") + "\n");
907
1006
 
908
1007
  // Pull the YATS Docker image from GitHub Container Registry
@@ -996,10 +1095,12 @@ async function main(options = {}) {
996
1095
  }
997
1096
  }
998
1097
  } else {
999
- // Windows: use setx (no visual feedback needed for the spinner)
1000
- // setx is best-effort; user may need admin
1098
+ // Windows: update the USER Path via the registry through PowerShell.
1099
+ // setx would truncate values >1024 chars, store the literal "%PATH%"
1100
+ // (no shell expansion happens under CreateProcess), and rewrite the
1101
+ // REG_EXPAND_SZ value as REG_SZ — corrupting the user's PATH.
1001
1102
  try {
1002
- await runCmd("setx", ["PATH", `${YATS_BIN_DIR};%PATH%`]);
1103
+ await runCmd("powershell", ["-NoProfile", "-NonInteractive", "-Command", windowsPathPowerShell(YATS_BIN_DIR)]);
1003
1104
  } catch {}
1004
1105
  }
1005
1106
 
@@ -1016,14 +1117,14 @@ async function main(options = {}) {
1016
1117
 
1017
1118
  // Done
1018
1119
  console.log("");
1019
- console.log(` ✅ ${G}YATS is ready!${R} → ${C}http://localhost:${mcpPort}/mcp/sse${R}`);
1120
+ console.log(` ✅ ${G}YATS is ready!${R} → ${C}http://localhost:${mcpPort}/mcp${R}`);
1020
1121
  console.log("");
1021
1122
  console.log(` Config saved to ${C}~/.yats/.env${R}`);
1022
1123
  console.log(` ${D}Benchmark agent keys (ANTHROPIC_API_KEY, OPENAI_API_KEY, GEMINI_API_KEY) go there too.${R}`);
1023
1124
  console.log("");
1024
1125
  box([
1025
1126
  `${B}Copy this URL into your AI agent:${R}`,
1026
- `{ "url": "http://localhost:${mcpPort}/mcp/sse" }`,
1127
+ `{ "url": "http://localhost:${mcpPort}/mcp" }`,
1027
1128
  "",
1028
1129
  `${B}Copilot / Claude Desktop:${R}`,
1029
1130
  `{ "command": "npx", "args": ["yats-bridge"] }`,
package/src/setup.test.js CHANGED
@@ -1,14 +1,17 @@
1
1
  /**
2
- * Tests — setup wizard env persistence (applyEnvKeys).
2
+ * Tests — setup wizard env persistence (applyEnvKeys), generated docker-compose
3
+ * (generateCompose), and the Windows PATH helper (windowsPathPowerShell).
3
4
  *
4
- * Covers the Azure OpenAI provider, custom endpoints for OpenAI-compatible
5
- * providers, and reconfiguration between providers.
5
+ * The compose tests parse the generated YAML so any indentation regression in
6
+ * the embedded template (e.g. the ollama service leaking into another service
7
+ * or a volume becoming a service) fails here instead of on a user's machine.
6
8
  */
7
9
 
8
10
  import { describe, it } from "node:test";
9
11
  import assert from "node:assert/strict";
12
+ import YAML from "yaml";
10
13
 
11
- import { applyEnvKeys } from "./setup.js";
14
+ import { applyEnvKeys, generateCompose, windowsPathPowerShell } from "./setup.js";
12
15
 
13
16
  describe("applyEnvKeys", () => {
14
17
  it("persists Azure OpenAI endpoint, key, model, and api version", () => {
@@ -86,4 +89,101 @@ describe("applyEnvKeys", () => {
86
89
  assert.equal(env.GEMINI_API_KEY, "");
87
90
  assert.equal(env.DEEPSEEK_API_KEY, "");
88
91
  });
92
+
93
+ it("persists an external Ollama URL and clears it for container mode", () => {
94
+ const env = applyEnvKeys({}, {
95
+ provider: "ollama",
96
+ model: "nomic-embed-text",
97
+ ollamaUrl: "http://host.docker.internal:11434",
98
+ });
99
+ assert.equal(env.OLLAMA_URL, "http://host.docker.internal:11434");
100
+
101
+ // Choosing the bundled container clears any external URL so the compose
102
+ // falls back to its default (http://ollama:11434).
103
+ const containerMode = applyEnvKeys(env, {
104
+ provider: "ollama",
105
+ model: "nomic-embed-text",
106
+ ollamaUrl: "http://ollama:11434",
107
+ });
108
+ assert.ok(!("OLLAMA_URL" in containerMode));
109
+
110
+ const noUrl = applyEnvKeys(containerMode, {
111
+ provider: "ollama",
112
+ model: "mxbai-embed-large",
113
+ });
114
+ assert.ok(!("OLLAMA_URL" in noUrl));
115
+ });
116
+ });
117
+
118
+ describe("generateCompose", () => {
119
+ function parseCompose(provider, ollamaUrl = "") {
120
+ const compose = generateCompose(provider, 5555, 4, true, 300, ollamaUrl);
121
+ const doc = YAML.parse(compose);
122
+ assert.ok(doc.services, "services section missing");
123
+ return doc;
124
+ }
125
+
126
+ it("generates valid YAML with the core services for every provider", () => {
127
+ for (const provider of ["ollama", "openai", "azure", "mistral", "voyage"]) {
128
+ const doc = parseCompose(provider);
129
+ assert.ok(doc.services.neo4j, `neo4j missing (${provider})`);
130
+ assert.ok(doc.services.qdrant, `qdrant missing (${provider})`);
131
+ assert.ok(doc.services.yats, `yats missing (${provider})`);
132
+ assert.ok("neo4j-data" in doc.volumes, `neo4j-data volume missing (${provider})`);
133
+ }
134
+ });
135
+
136
+ it("bundles a top-level Ollama service and its volume (container mode)", () => {
137
+ const doc = parseCompose("ollama");
138
+
139
+ // Regression guard: the ollama service used to be emitted misindented
140
+ // (nested under qdrant) and its volume ended up parsed as a service.
141
+ assert.ok(doc.services.ollama, "ollama service missing");
142
+ assert.equal(doc.services.ollama.image, "ollama/ollama:latest");
143
+ assert.ok(doc.services.qdrant.ollama === undefined, "ollama leaked into qdrant");
144
+ assert.ok(!doc.services["ollama-models"], "volume became a service");
145
+ assert.ok("ollama-models" in doc.volumes, "ollama-models volume missing");
146
+
147
+ // The yats container must reach a host-installed Ollama on any platform.
148
+ assert.deepEqual(
149
+ doc.services.yats.extra_hosts,
150
+ ["host.docker.internal:host-gateway"],
151
+ );
152
+ // The URL comes from .env at compose time with a sane default.
153
+ assert.ok(
154
+ doc.services.yats.environment.includes("OLLAMA_URL=${OLLAMA_URL:-http://ollama:11434}"),
155
+ );
156
+ });
157
+
158
+ it("omits the Ollama service when an external Ollama is used", () => {
159
+ const doc = parseCompose("ollama", "http://host.docker.internal:11434");
160
+ assert.ok(!doc.services.ollama, "ollama service should be omitted");
161
+ assert.ok(!("ollama-models" in doc.volumes), "ollama volume should be omitted");
162
+ assert.deepEqual(
163
+ doc.services.yats.extra_hosts,
164
+ ["host.docker.internal:host-gateway"],
165
+ );
166
+ });
167
+
168
+ it("omits Ollama for non-ollama providers", () => {
169
+ const doc = parseCompose("openai");
170
+ assert.ok(!doc.services.ollama, "ollama service should be omitted");
171
+ assert.ok(!("ollama-models" in doc.volumes), "ollama volume should be omitted");
172
+ });
173
+ });
174
+
175
+ describe("windowsPathPowerShell", () => {
176
+ it("builds an idempotent, non-truncating, REG_EXPAND_SZ PATH update", () => {
177
+ const cmd = windowsPathPowerShell("C:\\Users\\franco\\.yats\\bin");
178
+ assert.match(cmd, /GetEnvironmentVariable\('Path','User'\)/);
179
+ assert.match(cmd, /SetValue\('HKEY_CURRENT_USER\\Environment','Path'/);
180
+ assert.match(cmd, /'ExpandString'/);
181
+ assert.ok(!cmd.includes("%PATH%"), "must not write a literal %PATH%");
182
+ assert.ok(!cmd.includes("setx"), "must not use setx");
183
+ });
184
+
185
+ it("escapes single quotes in the bin directory", () => {
186
+ const cmd = windowsPathPowerShell("C:\\Users\\o'reilly\\.yats\\bin");
187
+ assert.match(cmd, /o''reilly/);
188
+ });
89
189
  });