@tacitai/mcp-server 0.6.44 → 0.6.46

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -4,7 +4,7 @@ import * as path from 'path';
4
4
  import * as os from 'os';
5
5
  import * as readline from 'readline';
6
6
  import { spawn } from 'child_process';
7
- import { deviceAuthFlow, deriveAppUrl, workspaceNameToProfile } from './setup.js';
7
+ import { deviceAuthFlow, loginFlow, deriveAppUrl, workspaceNameToProfile } from './setup.js';
8
8
  const PROFILES_DIR = path.join(os.homedir(), '.tacit', 'profiles');
9
9
  const DEFAULT_FILE = path.join(os.homedir(), '.tacit', 'default');
10
10
  const PROFILE_REGEX = /^[a-z0-9][a-z0-9-]{0,63}$/;
@@ -163,22 +163,27 @@ async function cmdLogin(args) {
163
163
  try {
164
164
  result = await deviceAuthFlow(apiUrl);
165
165
  }
166
- catch (err) {
167
- const msg = err instanceof Error ? err.message : String(err);
166
+ catch (deviceErr) {
167
+ const msg = deviceErr instanceof Error ? deviceErr.message : String(deviceErr);
168
168
  if (msg.includes('timed out')) {
169
169
  process.stderr.write('Authentication timed out (120s). Try again or check browser.\n');
170
+ process.exit(1);
171
+ return;
170
172
  }
171
173
  else if (msg.includes('state mismatch')) {
172
174
  process.stderr.write('Authentication failed: state mismatch. Try again.\n');
175
+ process.exit(1);
176
+ return;
173
177
  }
174
178
  else if (msg.includes('EADDRINUSE')) {
175
179
  process.stderr.write('Port 9123 busy (another login running?). Try again.\n');
180
+ process.exit(1);
181
+ return;
176
182
  }
177
- else {
178
- process.stderr.write(`Authentication failed: ${msg}\n`);
179
- }
180
- process.exit(1);
181
- return;
183
+ // Device-auth not available (e.g. 404) — fall back to PIN login.
184
+ process.stderr.write(' Browser sign-in not available. Falling back to email + PIN.\n');
185
+ const loginResult = await loginFlow(apiUrl);
186
+ result = { token: loginResult.token, expiresAt: loginResult.expiresAt, workspaceName: loginResult.workspaceName };
182
187
  }
183
188
  let workspaceId;
184
189
  let displayName = result.workspaceName;
package/dist/setup.d.ts CHANGED
@@ -48,6 +48,7 @@ export declare function deriveAppUrl(apiUrl: string): string;
48
48
  /**
49
49
  * Write ~/.tacit/profiles/<profile>.json with { expires_at, api_url }.
50
50
  * Token plaintext is NEVER written here — metadata only.
51
+ * @deprecated Prefer writeV2Profile for full profile data.
51
52
  */
52
53
  export declare function writeProfileMetadata(profile: string, expiresAt: string, apiUrl: string): void;
53
54
  interface DeviceAuthResult {
@@ -71,5 +72,11 @@ interface DeviceAuthResult {
71
72
  * - Browser open fails → print URL to stdout for manual copy-paste (AC-16 fallback).
72
73
  */
73
74
  export declare function deviceAuthFlow(apiUrl: string): Promise<DeviceAuthResult>;
75
+ interface LoginResult {
76
+ token: string;
77
+ workspaceName: string;
78
+ expiresAt: string;
79
+ }
80
+ export declare function loginFlow(apiUrl: string): Promise<LoginResult>;
74
81
  export declare function setup(argv: string[]): Promise<void>;
75
82
  export {};
package/dist/setup.js CHANGED
@@ -189,10 +189,27 @@ function mergeConfig(existing, profileName, entry) {
189
189
  function configToBytes(cfg) {
190
190
  return JSON.stringify(cfg, null, 2) + '\n';
191
191
  }
192
- // ─── Metadata file ────────────────────────────────────────────────────────────
192
+ function writeV2Profile(name, data) {
193
+ if (!/^[a-z0-9][a-z0-9-]{0,63}$/.test(name)) {
194
+ process.stderr.write(`[TACIT] Invalid profile name '${name}' — skipping profile write.\n`);
195
+ return;
196
+ }
197
+ const metaDir = path.join(os.homedir(), '.tacit', 'profiles');
198
+ fs.mkdirSync(metaDir, { recursive: true, mode: 0o700 });
199
+ try {
200
+ fs.chmodSync(metaDir, 0o700);
201
+ }
202
+ catch { /* unsupported OS */ }
203
+ const filePath = path.join(metaDir, `${name}.json`);
204
+ const tmp = filePath + '.tmp';
205
+ fs.writeFileSync(tmp, JSON.stringify(data, null, 2) + '\n', { mode: 0o600 });
206
+ fs.renameSync(tmp, filePath);
207
+ }
208
+ // ─── Metadata file (legacy v1) ───────────────────────────────────────────────
193
209
  /**
194
210
  * Write ~/.tacit/profiles/<profile>.json with { expires_at, api_url }.
195
211
  * Token plaintext is NEVER written here — metadata only.
212
+ * @deprecated Prefer writeV2Profile for full profile data.
196
213
  */
197
214
  export function writeProfileMetadata(profile, expiresAt, apiUrl) {
198
215
  if (!/^[a-z0-9][a-z0-9-]{0,63}$/.test(profile)) {
@@ -401,7 +418,7 @@ function prompt(question, hidden = false) {
401
418
  }
402
419
  });
403
420
  }
404
- async function loginFlow(apiUrl) {
421
+ export async function loginFlow(apiUrl) {
405
422
  process.stderr.write('\n Log in with your TACIT credentials.\n\n');
406
423
  const email = await prompt(' Email: ');
407
424
  const pin = await prompt(' PIN: ', true);
@@ -434,11 +451,12 @@ async function loginFlow(apiUrl) {
434
451
  const data = await res.json();
435
452
  const token = typeof data['session_token'] === 'string' ? data['session_token'] : '';
436
453
  const workspaceName = typeof data['workspace_name'] === 'string' ? data['workspace_name'] : '';
454
+ const expiresAt = typeof data['expires_at'] === 'string' ? data['expires_at'] : '';
437
455
  if (!token) {
438
456
  process.stderr.write('Error: login returned no session token.\n');
439
457
  process.exit(1);
440
458
  }
441
- return { token, workspaceName };
459
+ return { token, workspaceName, expiresAt };
442
460
  }
443
461
  // ─── Smoke synthesis ──────────────────────────────────────────────────────────
444
462
  const SMOKE_QUERY = 'What is in this knowledge base?';
@@ -512,22 +530,69 @@ export async function setup(argv) {
512
530
  if (!authenticated) {
513
531
  const loginResult = await loginFlow(apiUrl);
514
532
  token = loginResult.token;
533
+ if (loginResult.expiresAt)
534
+ expiresAt = loginResult.expiresAt;
515
535
  if (!opts.profileExplicit && loginResult.workspaceName) {
516
536
  profile = workspaceNameToProfile(loginResult.workspaceName);
517
537
  }
518
538
  }
519
539
  }
520
- // Final env-var name derived from (possibly updated) profile.
521
- const envVarName = profileToEnvVar(profile);
522
- // Pass the actual token when we have it (device-auth or --token);
523
- // fall back to env-var placeholder when the token came from the environment.
540
+ let allWorkspaces = [];
541
+ let activeWorkspaceId = '';
542
+ if (token) {
543
+ try {
544
+ const wsResp = await fetch(apiUrl.endsWith('/api/v1')
545
+ ? `${apiUrl}/workspaces/mine`
546
+ : `${apiUrl}/api/v1/workspaces/mine`, { headers: { 'Authorization': `Bearer ${token}`, 'Accept': 'application/json' } });
547
+ if (wsResp.ok) {
548
+ const wsData = await wsResp.json();
549
+ activeWorkspaceId = typeof wsData['active_workspace_id'] === 'string' ? wsData['active_workspace_id'] : '';
550
+ if (Array.isArray(wsData['workspaces'])) {
551
+ for (const w of wsData['workspaces']) {
552
+ const wsId = typeof w['workspace_id'] === 'string' ? w['workspace_id']
553
+ : typeof w['id'] === 'string' ? w['id'] : '';
554
+ const wsName = typeof w['display_name'] === 'string' ? w['display_name']
555
+ : typeof w['name'] === 'string' ? w['name'] : '';
556
+ if (wsId && wsName) {
557
+ allWorkspaces.push({
558
+ id: wsId,
559
+ name: wsName,
560
+ profileName: workspaceNameToProfile(wsName),
561
+ });
562
+ }
563
+ }
564
+ }
565
+ }
566
+ }
567
+ catch { /* workspace resolution failed — will fall back to single-profile mode */ }
568
+ }
569
+ // If explicit --profile was given, use only the active workspace with that name.
570
+ // Otherwise derive profile name per workspace.
571
+ const activeWs = allWorkspaces.find(w => w.id === activeWorkspaceId);
572
+ if (opts.profileExplicit) {
573
+ // Explicit profile: write one profile for the active workspace.
574
+ if (activeWs) {
575
+ allWorkspaces = [{ ...activeWs, profileName: profile }];
576
+ }
577
+ }
578
+ else if (activeWs) {
579
+ profile = activeWs.profileName;
580
+ }
581
+ // The MCP server is always registered as "tacit" — one generic server that
582
+ // resolves workspace identity via the profile system at runtime.
583
+ const mcpServerName = 'tacit';
524
584
  const resolvedToken = token ?? null;
525
- const profileEntry = buildProfileEntry(apiUrl, envVarName, resolvedToken);
585
+ // Build the MCP server entry without embedding a token — the server resolves
586
+ // credentials from the default profile (~/.tacit/default → profile file).
587
+ const profileEntry = buildProfileEntry(apiUrl, 'TACIT_TOKEN', null);
588
+ // Remove the placeholder token — the server should resolve via profiles, not env vars.
589
+ // Keep TACIT_API_URL as a fallback hint.
590
+ delete profileEntry.env['TACIT_TOKEN'];
526
591
  // D10: emit confirmation string BEFORE writing (also printed in dry-run).
527
- process.stdout.write(`\n Registering MCP server "${profile}" with Claude Code...\n`);
592
+ process.stdout.write(`\n Registering MCP server "${mcpServerName}" with Claude Code...\n`);
528
593
  if (opts.dryRun) {
529
594
  process.stdout.write(' (dry-run) Would register:\n');
530
- const redactedEntry = buildProfileEntry(apiUrl, envVarName, null);
595
+ const redactedEntry = buildProfileEntry(apiUrl, 'TACIT_TOKEN', null);
531
596
  process.stdout.write(` ${JSON.stringify(redactedEntry, null, 2)}\n`);
532
597
  process.exit(0);
533
598
  return;
@@ -536,7 +601,7 @@ export async function setup(argv) {
536
601
  // Writing ~/.claude/mcp.json directly does NOT work (Claude Code ignores that file).
537
602
  const jsonConfig = JSON.stringify(profileEntry);
538
603
  const registered = await new Promise((resolve) => {
539
- execFile('claude', ['mcp', 'add-json', '--scope', 'user', profile, jsonConfig], {
604
+ execFile('claude', ['mcp', 'add-json', '--scope', 'user', mcpServerName, jsonConfig], {
540
605
  timeout: 15_000,
541
606
  }, (err, stdout, stderr) => {
542
607
  if (err) {
@@ -555,13 +620,55 @@ export async function setup(argv) {
555
620
  fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
556
621
  }
557
622
  const existing = readExistingConfig();
558
- const merged = mergeConfig(existing, profile, profileEntry);
623
+ const merged = mergeConfig(existing, mcpServerName, profileEntry);
559
624
  const output = configToBytes(merged);
560
625
  const dest = mcpJsonPath();
561
626
  fs.writeFileSync(dest, output, { encoding: 'utf-8', mode: 0o600 });
562
627
  fs.chmodSync(dest, 0o600);
563
- // AC-12: write ~/.tacit/profiles/<profile>.json metadata (token NOT included).
564
- if (expiresAt) {
628
+ // Write v2 profiles for ALL workspaces the user has access to.
629
+ const writtenProfiles = [];
630
+ if (resolvedToken && allWorkspaces.length > 0) {
631
+ for (const ws of allWorkspaces) {
632
+ writeV2Profile(ws.profileName, {
633
+ version: 2,
634
+ workspace_id: ws.id,
635
+ workspace_name: ws.name,
636
+ api_url: apiUrl,
637
+ app_url: deriveAppUrl(apiUrl),
638
+ token: resolvedToken,
639
+ created_at: new Date().toISOString(),
640
+ expires_at: expiresAt || undefined,
641
+ });
642
+ writtenProfiles.push(ws.profileName);
643
+ }
644
+ // Set the active workspace as default profile.
645
+ const defaultFile = path.join(os.homedir(), '.tacit', 'default');
646
+ const defaultProfile = activeWs ? activeWs.profileName : allWorkspaces[0].profileName;
647
+ const dir = path.dirname(defaultFile);
648
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
649
+ fs.writeFileSync(defaultFile, defaultProfile + '\n', { mode: 0o600 });
650
+ }
651
+ else if (resolvedToken) {
652
+ // Fallback: no workspace list available — write a single profile.
653
+ writeV2Profile(profile, {
654
+ version: 2,
655
+ workspace_id: '',
656
+ workspace_name: profile,
657
+ api_url: apiUrl,
658
+ app_url: deriveAppUrl(apiUrl),
659
+ token: resolvedToken,
660
+ created_at: new Date().toISOString(),
661
+ expires_at: expiresAt || undefined,
662
+ });
663
+ writtenProfiles.push(profile);
664
+ const defaultFile = path.join(os.homedir(), '.tacit', 'default');
665
+ if (!fs.existsSync(defaultFile)) {
666
+ const dir = path.dirname(defaultFile);
667
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
668
+ fs.writeFileSync(defaultFile, profile + '\n', { mode: 0o600 });
669
+ }
670
+ }
671
+ else if (expiresAt) {
565
672
  writeProfileMetadata(profile, expiresAt, apiUrl);
566
673
  }
567
674
  if (registered) {
@@ -570,14 +677,27 @@ export async function setup(argv) {
570
677
  else if (resolvedToken) {
571
678
  process.stdout.write(`\n Config written to ~/.claude/mcp.json (fallback).\n` +
572
679
  ` If Claude Code doesn't pick it up, run:\n` +
573
- ` claude mcp add-json --scope user ${profile} '${jsonConfig}'\n` +
680
+ ` claude mcp add-json --scope user ${mcpServerName} '${jsonConfig}'\n` +
574
681
  ` Then start a new Claude Code session.\n`);
575
682
  }
576
683
  else {
577
684
  process.stdout.write(`\n Setup complete. Add this to your shell profile:\n` +
578
- ` export ${envVarName}=<your-token>\n` +
685
+ ` export TACIT_TOKEN=<your-token>\n` +
579
686
  `\n Then start a new Claude Code session to connect.\n`);
580
687
  }
688
+ // Show all profiles that were written.
689
+ if (writtenProfiles.length > 0) {
690
+ process.stdout.write(`\n Profiles saved:\n`);
691
+ for (const p of writtenProfiles) {
692
+ const isDefault = activeWs ? p === activeWs.profileName : p === writtenProfiles[0];
693
+ process.stdout.write(` ${isDefault ? '* ' : ' '}${p}\n`);
694
+ }
695
+ process.stdout.write(`\n Launch Claude Code with a workspace:\n` +
696
+ ` tacit launch ${writtenProfiles[0]}` +
697
+ (writtenProfiles.length > 1 ? ` # or: tacit launch ${writtenProfiles[1]}` : '') +
698
+ `\n\n List profiles: tacit ls\n` +
699
+ ` Set default: tacit use <name>\n`);
700
+ }
581
701
  if (opts.smoke) {
582
702
  await runSmoke(apiUrl, token);
583
703
  // runSmoke calls process.exit internally; return here for type safety.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tacitai/mcp-server",
3
- "version": "0.6.44",
3
+ "version": "0.6.46",
4
4
  "description": "stdio MCP server wrapping Tacit /api/v1 REST/SSE API",
5
5
  "license": "UNLICENSED",
6
6
  "repository": {