@tacitai/mcp-server 0.7.0 → 0.8.1

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 (73) hide show
  1. package/dist/api-errors.d.ts +102 -0
  2. package/dist/api-errors.js +165 -0
  3. package/dist/autonomy.d.ts +46 -0
  4. package/dist/autonomy.js +118 -0
  5. package/dist/claude-config.d.ts +139 -0
  6. package/dist/claude-config.js +339 -0
  7. package/dist/cli-launch.d.ts +33 -0
  8. package/dist/cli-launch.js +178 -0
  9. package/dist/cli-login.d.ts +34 -0
  10. package/dist/cli-login.js +200 -0
  11. package/dist/cli-mode.d.ts +47 -0
  12. package/dist/cli-mode.js +170 -0
  13. package/dist/cli-profiles.d.ts +37 -0
  14. package/dist/cli-profiles.js +344 -0
  15. package/dist/cli.d.ts +9 -0
  16. package/dist/cli.js +59 -458
  17. package/dist/client.d.ts +90 -52
  18. package/dist/client.js +198 -296
  19. package/dist/credentials.d.ts +81 -0
  20. package/dist/credentials.js +291 -0
  21. package/dist/index.d.ts +3 -3
  22. package/dist/index.js +37 -89
  23. package/dist/oauth.d.ts +1 -1
  24. package/dist/oauth.js +5 -5
  25. package/dist/profile-store.d.ts +96 -0
  26. package/dist/profile-store.js +382 -0
  27. package/dist/prompt.d.ts +32 -0
  28. package/dist/prompt.js +99 -0
  29. package/dist/prompts.d.ts +2 -2
  30. package/dist/prompts.js +3 -3
  31. package/dist/server-mode.d.ts +65 -0
  32. package/dist/server-mode.js +99 -0
  33. package/dist/setup-migrate.d.ts +35 -0
  34. package/dist/setup-migrate.js +204 -0
  35. package/dist/setup.d.ts +41 -66
  36. package/dist/setup.js +361 -531
  37. package/dist/signin.d.ts +108 -0
  38. package/dist/signin.js +595 -0
  39. package/dist/tools/agents.d.ts +6 -4
  40. package/dist/tools/agents.js +15 -4
  41. package/dist/tools/artifacts.d.ts +2 -0
  42. package/dist/tools/artifacts.js +8 -1
  43. package/dist/tools/capture.js +2 -2
  44. package/dist/tools/career.js +2 -2
  45. package/dist/tools/chronicle.js +7 -7
  46. package/dist/tools/crews.js +8 -8
  47. package/dist/tools/errors.d.ts +18 -0
  48. package/dist/tools/errors.js +73 -1
  49. package/dist/tools/exec-route.d.ts +34 -0
  50. package/dist/tools/exec-route.js +101 -27
  51. package/dist/tools/github.js +2 -2
  52. package/dist/tools/gm.js +2 -2
  53. package/dist/tools/iam.js +2 -3
  54. package/dist/tools/kb.js +2 -2
  55. package/dist/tools/lake-structure.js +8 -8
  56. package/dist/tools/lake.js +2 -2
  57. package/dist/tools/onboarding.js +2 -2
  58. package/dist/tools/people.js +7 -7
  59. package/dist/tools/pyramid.js +2 -2
  60. package/dist/tools/recall.js +2 -2
  61. package/dist/tools/secretary.d.ts +1 -0
  62. package/dist/tools/secretary.js +2 -1
  63. package/dist/tools/synthesize.d.ts +37 -0
  64. package/dist/tools/synthesize.js +128 -9
  65. package/dist/tools/voice.d.ts +3 -2
  66. package/dist/tools/voice.js +70 -18
  67. package/dist/tools/wiki.js +2 -2
  68. package/dist/tools/workspaces.js +20 -6
  69. package/dist/version.d.ts +6 -0
  70. package/dist/version.js +18 -0
  71. package/dist/workflow-registry.d.ts +1 -0
  72. package/dist/workflow-registry.js +21 -0
  73. package/package.json +4 -1
@@ -0,0 +1,81 @@
1
+ /**
2
+ * Credential resolution and identity check (MV-1542c step 1.4).
3
+ *
4
+ * This is the ONLY module that reads TACIT_TOKEN, TACIT_API_URL, TACIT_WORKSPACE_ID,
5
+ * TACIT_APP_URL, TACIT_SESSION_TOKEN and TACIT_PROFILE. The first level that matches wins:
6
+ *
7
+ * 0 env triple TACIT_TOKEN + TACIT_API_URL + TACIT_WORKSPACE_ID all set (oracles, evals;
8
+ * overrides TACIT_PROFILE, BUG-402)
9
+ * 1 TACIT_PROFILE safe-load the named profile
10
+ * 2 env any of TACIT_TOKEN / TACIT_SESSION_TOKEN (backward compat); API URL falls
11
+ * back to localhost; TACIT_WORKSPACE_ID without a token is an error
12
+ * 4 default ~/.tacit/default names a profile; safe-load it
13
+ * 5 none signed out; never contacts a default server (D-52)
14
+ *
15
+ * (Level 3, the sync.json workspace hint, stays in TacitClient: it carries no credential.)
16
+ *
17
+ * Failures that must be visible are thrown as CredentialError with the spec message
18
+ * (§ Error Handling): broken default, unsafe or JWT profile, expired login, API-URL
19
+ * conflict. There is no fallback to another credential, workspace, server or identity.
20
+ *
21
+ * A saved login is sent only to its own server (URL lock): at levels 1 and 4 the profile's
22
+ * api_url is always the one used, and a TACIT_API_URL on another host is an error.
23
+ *
24
+ * Tokens never appear in a message or a log line.
25
+ */
26
+ import { type ProfileData } from './profile-store.js';
27
+ import { type TacitClient, type TacitClientOptions, type WhoAmI } from './client.js';
28
+ export type CredentialSource = {
29
+ level: 0;
30
+ kind: 'env-triple';
31
+ } | {
32
+ level: 1;
33
+ kind: 'profile';
34
+ profile: string;
35
+ via: 'TACIT_PROFILE';
36
+ } | {
37
+ level: 2;
38
+ kind: 'env';
39
+ } | {
40
+ level: 4;
41
+ kind: 'profile';
42
+ profile: string;
43
+ via: 'default';
44
+ } | {
45
+ level: 5;
46
+ kind: 'none';
47
+ };
48
+ export interface ResolvedCredentials {
49
+ options: TacitClientOptions;
50
+ source: CredentialSource;
51
+ profile?: ProfileData;
52
+ warnings: string[];
53
+ }
54
+ /** A startup-blocking credential problem; `message` is the exact text to show. */
55
+ export declare class CredentialError extends Error {
56
+ readonly source: CredentialSource;
57
+ constructor(message: string, source: CredentialSource);
58
+ }
59
+ /** Level-2 API URL when only a token is exported. Never used for a signed-out start. */
60
+ export declare const LEVEL2_DEFAULT_API_URL = "http://localhost:7473";
61
+ export declare function resolveCredentials(env?: NodeJS.ProcessEnv, now?: number): ResolvedCredentials;
62
+ export type IdentityCheck = {
63
+ status: 'verified';
64
+ who: WhoAmI;
65
+ } | {
66
+ status: 'unsupported';
67
+ httpStatus: 404 | 405;
68
+ } | {
69
+ status: 'unreachable';
70
+ cause: string;
71
+ };
72
+ export declare class StartupFault extends Error {
73
+ readonly code: 'WORKSPACE_MISMATCH' | 'TOKEN_REJECTED' | 'ACCESS_REMOVED' | 'KIND_NOT_ALLOWED';
74
+ constructor(code: 'WORKSPACE_MISMATCH' | 'TOKEN_REJECTED' | 'ACCESS_REMOVED' | 'KIND_NOT_ALLOWED', message: string);
75
+ }
76
+ /**
77
+ * Ask the server who this credential is. Throws StartupFault for a login that is rejected, removed,
78
+ * of the wrong kind, or for another workspace than its profile names. Returns `unsupported` (old
79
+ * server) or `unreachable` (network, 5xx) without judging the credential.
80
+ */
81
+ export declare function verifyIdentity(client: Pick<TacitClient, 'whoami'>, resolved: ResolvedCredentials): Promise<IdentityCheck>;
@@ -0,0 +1,291 @@
1
+ /**
2
+ * Credential resolution and identity check (MV-1542c step 1.4).
3
+ *
4
+ * This is the ONLY module that reads TACIT_TOKEN, TACIT_API_URL, TACIT_WORKSPACE_ID,
5
+ * TACIT_APP_URL, TACIT_SESSION_TOKEN and TACIT_PROFILE. The first level that matches wins:
6
+ *
7
+ * 0 env triple TACIT_TOKEN + TACIT_API_URL + TACIT_WORKSPACE_ID all set (oracles, evals;
8
+ * overrides TACIT_PROFILE, BUG-402)
9
+ * 1 TACIT_PROFILE safe-load the named profile
10
+ * 2 env any of TACIT_TOKEN / TACIT_SESSION_TOKEN (backward compat); API URL falls
11
+ * back to localhost; TACIT_WORKSPACE_ID without a token is an error
12
+ * 4 default ~/.tacit/default names a profile; safe-load it
13
+ * 5 none signed out; never contacts a default server (D-52)
14
+ *
15
+ * (Level 3, the sync.json workspace hint, stays in TacitClient: it carries no credential.)
16
+ *
17
+ * Failures that must be visible are thrown as CredentialError with the spec message
18
+ * (§ Error Handling): broken default, unsafe or JWT profile, expired login, API-URL
19
+ * conflict. There is no fallback to another credential, workspace, server or identity.
20
+ *
21
+ * A saved login is sent only to its own server (URL lock): at levels 1 and 4 the profile's
22
+ * api_url is always the one used, and a TACIT_API_URL on another host is an error.
23
+ *
24
+ * Tokens never appear in a message or a log line.
25
+ */
26
+ import * as fs from 'node:fs';
27
+ import { printable } from './api-errors.js';
28
+ import { readProfile, getDefault, defaultFilePath, profilePath, ProfileError, } from './profile-store.js';
29
+ import { TacitApiError, TokenExpiredError, } from './client.js';
30
+ /** A startup-blocking credential problem; `message` is the exact text to show. */
31
+ export class CredentialError extends Error {
32
+ source;
33
+ constructor(message, source) {
34
+ super(message);
35
+ this.source = source;
36
+ this.name = 'CredentialError';
37
+ }
38
+ }
39
+ /** Level-2 API URL when only a token is exported. Never used for a signed-out start. */
40
+ export const LEVEL2_DEFAULT_API_URL = 'http://localhost:7473';
41
+ const NONE = { level: 5, kind: 'none' };
42
+ function envValue(env, key) {
43
+ const v = env[key]?.trim();
44
+ return v ? v : undefined;
45
+ }
46
+ function hostOf(url) {
47
+ try {
48
+ return new URL(url).host.toLowerCase();
49
+ }
50
+ catch {
51
+ return null;
52
+ }
53
+ }
54
+ /** ProfileError text without its trailing "Run: ..." / "Re-run: ..." hint and without repeated paths. */
55
+ function reasonOf(err, name, file) {
56
+ const label = `Profile '${name}' `;
57
+ const text = err.message.startsWith(label) ? err.message.slice(label.length) : err.message;
58
+ return text
59
+ .split(` at ${file}`).join('')
60
+ .split(`: ${file}`).join('')
61
+ .replace(/\.?\s+(?:Re-run|Run): [\s\S]*$/, '')
62
+ .trim();
63
+ }
64
+ const JWT_MESSAGE = 'This profile holds a browser login, not a CLI login. Run: tacit login';
65
+ function loadFailure(err, name, source, isDefault) {
66
+ if (!(err instanceof ProfileError))
67
+ throw err;
68
+ if (err.code === 'JWT_TOKEN')
69
+ return new CredentialError(JWT_MESSAGE, source);
70
+ const reason = reasonOf(err, name, profilePath(name));
71
+ const message = isDefault
72
+ ? `Default profile ${name} can't be used: ${reason}. Run: tacit login`
73
+ : `Profile ${name} was not loaded: ${profilePath(name)} ${reason}. Run: tacit login`;
74
+ return new CredentialError(message, source);
75
+ }
76
+ function checkExpiry(profile, source, now) {
77
+ if (!profile.expires_at)
78
+ return;
79
+ const expiresMs = Date.parse(profile.expires_at);
80
+ if (Number.isNaN(expiresMs) || now <= expiresMs)
81
+ return;
82
+ const date = new Date(expiresMs).toISOString().slice(0, 10);
83
+ throw new CredentialError(`Your login for ${profile.workspace_name ?? profile.workspace_id} expired on ${date}. Run: tacit login`, source);
84
+ }
85
+ /** URL lock: a saved login goes only to its own server. */
86
+ function checkUrlLock(env, profile, name, source) {
87
+ const envUrl = envValue(env, 'TACIT_API_URL');
88
+ if (!envUrl)
89
+ return;
90
+ const envHost = hostOf(envUrl);
91
+ const profileHost = hostOf(profile.api_url);
92
+ if (!envHost) {
93
+ throw new CredentialError(`TACIT_API_URL (${envUrl}) is not a valid URL. Unset it, or fix it.`, source);
94
+ }
95
+ if (!profileHost) {
96
+ throw new CredentialError(`Profile ${name} has an invalid api_url. Run: tacit login`, source);
97
+ }
98
+ if (envHost !== profileHost) {
99
+ throw new CredentialError(`TACIT_API_URL (${envHost}) differs from profile ${name} (${profileHost}). ` +
100
+ `A saved login is only sent to its own server. Unset TACIT_API_URL, or run: tacit login --api-url ${envUrl}`, source);
101
+ }
102
+ }
103
+ function fromProfile(env, profile, name, source, now) {
104
+ checkExpiry(profile, source, now);
105
+ checkUrlLock(env, profile, name, source);
106
+ return {
107
+ options: {
108
+ apiUrl: profile.api_url,
109
+ appUrl: profile.app_url ?? envValue(env, 'TACIT_APP_URL'),
110
+ token: profile.token,
111
+ workspaceId: profile.workspace_id,
112
+ workspaceName: profile.workspace_name,
113
+ },
114
+ source,
115
+ profile,
116
+ warnings: [],
117
+ };
118
+ }
119
+ /** Why `~/.tacit/default` exists but names nothing usable (getDefault() returns null for all of these). */
120
+ function brokenDefaultReason() {
121
+ let st;
122
+ try {
123
+ st = fs.lstatSync(defaultFilePath());
124
+ }
125
+ catch {
126
+ return null;
127
+ }
128
+ if (st.isSymbolicLink())
129
+ return 'the default file is a symlink';
130
+ if (!st.isFile())
131
+ return 'the default file is not a regular file';
132
+ if (process.platform !== 'win32') {
133
+ if (typeof process.getuid === 'function' && st.uid !== process.getuid()) {
134
+ return 'the default file is owned by another user';
135
+ }
136
+ if ((st.mode & 0o077) !== 0)
137
+ return 'the default file can be read by other users';
138
+ }
139
+ return 'the default file does not name a valid profile';
140
+ }
141
+ export function resolveCredentials(env = process.env, now = Date.now()) {
142
+ const token = envValue(env, 'TACIT_TOKEN');
143
+ const apiUrl = envValue(env, 'TACIT_API_URL');
144
+ const workspaceId = envValue(env, 'TACIT_WORKSPACE_ID');
145
+ const sessionToken = envValue(env, 'TACIT_SESSION_TOKEN');
146
+ const appUrl = envValue(env, 'TACIT_APP_URL');
147
+ const profileName = envValue(env, 'TACIT_PROFILE');
148
+ // Level 0: complete env triple (BUG-402). All three must be set so a stale single export cannot win.
149
+ if (token && apiUrl && workspaceId) {
150
+ const warnings = profileName ? [`explicit env var triple overrides TACIT_PROFILE=${profileName}`] : [];
151
+ return {
152
+ options: { apiUrl, token, workspaceId, appUrl, sessionToken },
153
+ source: { level: 0, kind: 'env-triple' },
154
+ warnings,
155
+ };
156
+ }
157
+ // Level 1: TACIT_PROFILE.
158
+ if (profileName) {
159
+ const source = { level: 1, kind: 'profile', profile: profileName, via: 'TACIT_PROFILE' };
160
+ let profile;
161
+ try {
162
+ profile = readProfile(profileName);
163
+ }
164
+ catch (err) {
165
+ throw loadFailure(err, profileName, source, false);
166
+ }
167
+ return fromProfile(env, profile, profileName, source, now);
168
+ }
169
+ // Level 2: exported credentials (backward compat).
170
+ if (token || sessionToken || workspaceId) {
171
+ const source = { level: 2, kind: 'env' };
172
+ if (!token && !sessionToken) {
173
+ throw new CredentialError('TACIT_WORKSPACE_ID is set but TACIT_TOKEN is missing. Set TACIT_TOKEN, or unset TACIT_WORKSPACE_ID to use your saved login.', source);
174
+ }
175
+ return {
176
+ options: { apiUrl: apiUrl ?? LEVEL2_DEFAULT_API_URL, token, workspaceId, appUrl, sessionToken },
177
+ source,
178
+ warnings: [],
179
+ };
180
+ }
181
+ // Level 4: ~/.tacit/default. A default that exists but cannot be used is an error, never a silent signed-out start.
182
+ const defaultName = getDefault();
183
+ if (!defaultName) {
184
+ const reason = brokenDefaultReason();
185
+ if (reason) {
186
+ throw new CredentialError(`Default profile can't be used: ${reason}. Run: tacit login`, { level: 5, kind: 'none' });
187
+ }
188
+ return { options: {}, source: NONE, warnings: [] };
189
+ }
190
+ const source = { level: 4, kind: 'profile', profile: defaultName, via: 'default' };
191
+ let profile;
192
+ try {
193
+ profile = readProfile(defaultName);
194
+ }
195
+ catch (err) {
196
+ throw loadFailure(err, defaultName, source, true);
197
+ }
198
+ return fromProfile(env, profile, defaultName, source, now);
199
+ }
200
+ export class StartupFault extends Error {
201
+ code;
202
+ constructor(code, message) {
203
+ super(message);
204
+ this.code = code;
205
+ this.name = 'StartupFault';
206
+ }
207
+ }
208
+ function causeOf(err) {
209
+ const e = err;
210
+ const code = e?.cause?.code ?? e?.code;
211
+ return typeof code === 'string' ? code : typeof e?.name === 'string' ? e.name : 'network error';
212
+ }
213
+ function codeOfBody(body) {
214
+ try {
215
+ const p = JSON.parse(body);
216
+ const nested = p.error;
217
+ if (nested && typeof nested === 'object' && typeof nested.code === 'string')
218
+ return nested.code;
219
+ if (typeof p.code === 'string')
220
+ return p.code;
221
+ if (typeof nested === 'string')
222
+ return nested;
223
+ }
224
+ catch { /* not JSON */ }
225
+ return null;
226
+ }
227
+ const REMOVED_CODES = new Set(['ACCOUNT_DISABLED', 'MEMBERSHIP_INACTIVE', 'MEMBERSHIP_NOT_FOUND']);
228
+ function workspaceLabel(resolved) {
229
+ return printable(resolved.profile?.workspace_name ?? resolved.profile?.workspace_id ?? resolved.options.workspaceName ?? 'this workspace');
230
+ }
231
+ function rejectedMessage(resolved, code) {
232
+ if (code === 'CREDENTIAL_BINDING_MISMATCH') {
233
+ return `This login is no longer linked to a member of ${workspaceLabel(resolved)}. Run: tacit login`;
234
+ }
235
+ if (resolved.profile) {
236
+ return `Your TACIT login for ${workspaceLabel(resolved)} expired or was revoked. Sign in again: tacit login. ` +
237
+ 'Then restart Claude Code, or reconnect tacit with /mcp.';
238
+ }
239
+ const name = resolved.options.sessionToken && !resolved.options.token ? 'TACIT_SESSION_TOKEN' : 'TACIT_TOKEN';
240
+ return `The ${name} in your environment was rejected (expired or revoked). Replace it, or unset it to use your saved login.`;
241
+ }
242
+ /**
243
+ * Ask the server who this credential is. Throws StartupFault for a login that is rejected, removed,
244
+ * of the wrong kind, or for another workspace than its profile names. Returns `unsupported` (old
245
+ * server) or `unreachable` (network, 5xx) without judging the credential.
246
+ */
247
+ export async function verifyIdentity(client, resolved) {
248
+ let who;
249
+ try {
250
+ who = await client.whoami();
251
+ }
252
+ catch (err) {
253
+ if (err instanceof TokenExpiredError) {
254
+ if (err.code === 'MEMBERSHIP_NOT_FOUND') {
255
+ throw new StartupFault('ACCESS_REMOVED', `Your access to ${workspaceLabel(resolved)} was removed.`);
256
+ }
257
+ throw new StartupFault('TOKEN_REJECTED', rejectedMessage(resolved, err.code));
258
+ }
259
+ if (err instanceof TacitApiError) {
260
+ const code = codeOfBody(err.body);
261
+ if (err.statusCode === 404 || err.statusCode === 405)
262
+ return { status: 'unsupported', httpStatus: err.statusCode };
263
+ if (err.statusCode === 403) {
264
+ if (code && REMOVED_CODES.has(code)) {
265
+ throw new StartupFault('ACCESS_REMOVED', `Your access to ${workspaceLabel(resolved)} was removed.`);
266
+ }
267
+ throw new StartupFault('TOKEN_REJECTED', rejectedMessage(resolved, code));
268
+ }
269
+ return { status: 'unreachable', cause: `HTTP ${err.statusCode}` };
270
+ }
271
+ return { status: 'unreachable', cause: causeOf(err) };
272
+ }
273
+ const profile = resolved.profile;
274
+ if (profile) {
275
+ const name = resolved.source.level === 1 || resolved.source.level === 4 ? resolved.source.profile : 'profile';
276
+ if (who.credential_type !== 'iam_token' && who.credential_type !== 'dev_token') {
277
+ throw new StartupFault('KIND_NOT_ALLOWED', who.credential_type === 'jwt'
278
+ ? JWT_MESSAGE
279
+ : "This profile holds a credential that isn't a CLI login. Run: tacit login");
280
+ }
281
+ if (who.workspace_id.toLowerCase() !== profile.workspace_id.toLowerCase()) {
282
+ // A stored name equal to the token's name would read "for X but belongs to X" (id-only edit): name A by id then.
283
+ const tokenLabel = printable(who.workspace_name || who.workspace_id);
284
+ const profileLabel = profile.workspace_name && printable(profile.workspace_name) !== tokenLabel
285
+ ? printable(profile.workspace_name)
286
+ : profile.workspace_id;
287
+ throw new StartupFault('WORKSPACE_MISMATCH', `Profile ${name} is for ${profileLabel} but the token belongs to ${tokenLabel}. Run: tacit login`);
288
+ }
289
+ }
290
+ return { status: 'verified', who };
291
+ }
package/dist/index.d.ts CHANGED
@@ -4,12 +4,12 @@
4
4
  *
5
5
  * Transport: StdioServerTransport (NOT HTTP).
6
6
  * Per-cell invariant: spawned once per IDE session per user; never a daemon.
7
- * No network listener. All egress goes through TACIT_API_URL only.
7
+ * No network listener. All egress goes to the one API URL the resolved credential allows.
8
8
  *
9
9
  * Security invariants:
10
10
  * - No anthropic/openai import.
11
- * - TACIT_TOKEN never logged.
12
- * - Token from env only.
11
+ * - Tokens are never logged.
12
+ * - Credentials come from credentials.ts only (levels 0/1/2/4/5, URL lock).
13
13
  *
14
14
  * Compatibility guard (D-7 / KR4):
15
15
  * Reads own package.json compatibility.coreArtifact (semver range).
package/dist/index.js CHANGED
@@ -4,12 +4,12 @@
4
4
  *
5
5
  * Transport: StdioServerTransport (NOT HTTP).
6
6
  * Per-cell invariant: spawned once per IDE session per user; never a daemon.
7
- * No network listener. All egress goes through TACIT_API_URL only.
7
+ * No network listener. All egress goes to the one API URL the resolved credential allows.
8
8
  *
9
9
  * Security invariants:
10
10
  * - No anthropic/openai import.
11
- * - TACIT_TOKEN never logged.
12
- * - Token from env only.
11
+ * - Tokens are never logged.
12
+ * - Credentials come from credentials.ts only (levels 0/1/2/4/5, URL lock).
13
13
  *
14
14
  * Compatibility guard (D-7 / KR4):
15
15
  * Reads own package.json compatibility.coreArtifact (semver range).
@@ -25,9 +25,8 @@ import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'
25
25
  import * as semver from 'semver';
26
26
  import * as path from 'path';
27
27
  import * as fs from 'fs';
28
- import * as os from 'os';
29
28
  import { fileURLToPath } from 'url';
30
- import { TacitClient, getClient as getModuleClient } from './client.js';
29
+ import { getClient as getModuleClient, setDefaultClient } from './client.js';
31
30
  import { startHttpTransport } from './transport.js';
32
31
  // Tool registration modules
33
32
  import { registerSearchTools } from './tools/search.js';
@@ -70,9 +69,12 @@ import { registerCmoTools } from './tools/cmo.js';
70
69
  import { registerSecretaryTools } from './tools/secretary.js';
71
70
  import { registerIamTools, registerSecurityTools } from './tools/iam.js';
72
71
  import { registerPrompts } from './prompts.js';
73
- import { getRequestPrincipal, ensureAutonomy, resolveProfileOptions } from './client.js';
72
+ import { getRequestPrincipal } from './client.js';
73
+ import { ensureAutonomy } from './autonomy.js';
74
+ import { resolveStartup, registerStatusTool } from './server-mode.js';
75
+ import { readPackageVersion } from './version.js';
74
76
  // Setup wizard (MV-1057h / W5)
75
- import { setup, profileToEnvVar } from './setup.js';
77
+ import { setup } from './setup.js';
76
78
  import { WorkflowGate } from './workflow-gate.js';
77
79
  import { WorkflowPersistence } from './workflow-persistence.js';
78
80
  import { createDefaultRegistry } from './workflow-registry.js';
@@ -130,6 +132,11 @@ const GUIDANCE_MAP = {
130
132
  CTO_ENGINEERING: 'CTO Engineering active. Routes engineering requests to sub-execs (Agentic Engineering Exec). Describe the engineering need.',
131
133
  SECRETARY_CHRONICLE: 'Secretary active. Use tacit_secretary_log to record events, tacit_secretary_recall to search history.',
132
134
  CAREER_APPLICATION: 'Career application workflow active. Use tacit_career_* tools to manage campaigns, search/add jobs, generate tailored materials, and move jobs through pipeline stages.',
135
+ VOICE_COMPOSE: 'Voice composition: 1) tacit_voice_list_profiles; 2) assemble the grounded source text yourself; 3) tacit_compose_in_voice with content + query (omit content only for KB-grounded drafts); 4) if voice_match_degraded is true, show the user and stop for review.',
136
+ VOICE_RESOLVE: 'If composing in your voice: confirm exactly one profile is active, then assemble the grounded text and call tacit_compose_in_voice with content + query.',
137
+ VOICE_GROUND: 'Voice composition: assemble the grounded source text yourself (facts, draft, letter). Do not invent facts.',
138
+ VOICE_COMPOSE_STEP: 'Voice composition: call tacit_compose_in_voice with the grounded text in content and the instruction in query.',
139
+ VOICE_VERIFY: 'Voice composition: if voice_match_degraded is true, show the user and stop for review. Never claim a match you did not get.',
133
140
  };
134
141
  function expandGuidance(raw, _typeName, phase) {
135
142
  const expanded = GUIDANCE_MAP[raw];
@@ -154,7 +161,7 @@ function installPreCallHook(server) {
154
161
  registerArgs[handlerIdx] = async (...callArgs) => {
155
162
  const principal = getRequestPrincipal();
156
163
  const principalKey = principal ?? '__stdio__';
157
- const autonomyResult = await ensureAutonomy(principalKey);
164
+ const autonomyResult = await ensureAutonomy(principalKey, getModuleClient());
158
165
  if (typeof autonomyResult === 'object' && 'error' in autonomyResult) {
159
166
  return { content: [{ type: 'text', text: JSON.stringify(autonomyResult) }], isError: true };
160
167
  }
@@ -226,68 +233,22 @@ function checkCompatibility() {
226
233
  }
227
234
  }
228
235
  }
229
- // ─── Profile helpers ──────────────────────────────────────────────────────────
230
- function parseProfile(argv) {
231
- for (let i = 0; i < argv.length; i++) {
232
- if (argv[i] === '--profile' && argv[i + 1] && !argv[i + 1].startsWith('--')) {
233
- return argv[i + 1];
234
- }
235
- }
236
- return 'tacit';
237
- }
238
- function checkProfileExpiry(profile) {
239
- if (!/^[a-z0-9][a-z0-9-]{0,63}$/.test(profile))
240
- return;
241
- const metaPath = path.join(os.homedir(), '.tacit', 'profiles', `${profile}.json`);
242
- if (!fs.existsSync(metaPath)) {
243
- return;
244
- }
245
- let meta;
246
- try {
247
- meta = JSON.parse(fs.readFileSync(metaPath, 'utf-8'));
248
- }
249
- catch {
250
- return;
251
- }
252
- const expiresAt = typeof meta['expires_at'] === 'string' ? meta['expires_at'] : null;
253
- if (!expiresAt)
254
- return;
255
- const expiresMs = Date.parse(expiresAt);
256
- if (Number.isNaN(expiresMs))
257
- return;
258
- const nowMs = Date.now();
259
- const diffDays = Math.floor((expiresMs - nowMs) / (1000 * 60 * 60 * 24));
260
- if (diffDays < 14) {
261
- const apiUrl = typeof meta['api_url'] === 'string' ? meta['api_url'] : 'https://beta.tacitai.app';
262
- process.stderr.write(`[TACIT] Developer token expires in ${diffDays} day${diffDays === 1 ? '' : 's'}. ` +
263
- `Run: npx @tacitai/mcp-server setup --api-url ${apiUrl}\n`);
264
- }
265
- }
266
236
  // ─── Main ─────────────────────────────────────────────────────────────────────
267
237
  async function run() {
268
238
  if (process.argv.includes('--version') || process.argv.includes('-v')) {
269
- const pkgPath = path.join(__dirname, '..', 'package.json');
270
- try {
271
- const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf-8'));
272
- process.stdout.write(`${pkg.version}\n`);
273
- }
274
- catch {
239
+ const version = readPackageVersion();
240
+ if (version === 'unknown')
275
241
  process.stderr.write('unknown\n');
276
- }
242
+ else
243
+ process.stdout.write(`${version}\n`);
277
244
  return;
278
245
  }
279
246
  if (process.argv[2] === 'setup') {
280
247
  await setup(process.argv.slice(3));
281
248
  return;
282
249
  }
283
- const profile = parseProfile(process.argv.slice(2));
284
- const envVarName = profileToEnvVar(profile);
285
- if (envVarName !== 'TACIT_TOKEN' && process.env[envVarName] && !process.env['TACIT_TOKEN']) {
286
- process.env['TACIT_TOKEN'] = process.env[envVarName];
287
- }
288
- checkProfileExpiry(profile);
289
250
  checkCompatibility();
290
- const server = new McpServer({ name: '@tacitai/mcp-server', version: '0.3.0' }, {
251
+ const server = new McpServer({ name: '@tacitai/mcp-server', version: readPackageVersion() }, {
291
252
  capabilities: { tools: {}, prompts: {} },
292
253
  instructions: [
293
254
  'You have an executive team powered by TACIT. Each role handles a domain — route requests to the right role using tacit_exec_route.',
@@ -326,42 +287,29 @@ async function run() {
326
287
  ].join('\n'),
327
288
  });
328
289
  const isHttpMode = process.env['MCP_TRANSPORT'] === 'http';
329
- let clientInstance = null;
330
- // FEAT-255: resolve profile options once at startup (5-level chain). Skip in HTTP mode.
331
- let profileOpts;
290
+ // Resolve credentials once at startup (levels 0/1/2/4/5, URL lock, whoami). Skipped in HTTP mode,
291
+ // where every request carries its own credential.
292
+ let stdioClient = null;
332
293
  if (!isHttpMode) {
333
- try {
334
- profileOpts = resolveProfileOptions();
335
- // Propagate profile credentials to process.env so the module-level getClient()
336
- // singleton (used by ~107 tool call sites) picks up the correct identity.
337
- // Without this, tools would use stale env vars from the parent shell.
338
- if (profileOpts) {
339
- if (profileOpts.apiUrl)
340
- process.env['TACIT_API_URL'] = profileOpts.apiUrl;
341
- if (profileOpts.token)
342
- process.env['TACIT_TOKEN'] = profileOpts.token;
343
- if (profileOpts.workspaceId)
344
- process.env['TACIT_WORKSPACE_ID'] = profileOpts.workspaceId;
345
- }
346
- }
347
- catch (err) {
348
- const msg = err instanceof Error ? err.message : String(err);
349
- process.stderr.write(`[TACIT] Profile resolution failed: ${msg}\n`);
350
- if (process.env['TACIT_PROFILE']?.trim()) {
351
- process.stderr.write('[TACIT] TACIT_PROFILE was explicitly set — cannot continue without a valid profile.\n');
352
- process.exit(1);
353
- }
294
+ const startup = await resolveStartup();
295
+ for (const warning of startup.warnings)
296
+ process.stderr.write(`[TACIT] ${warning}\n`);
297
+ if (!('client' in startup)) {
298
+ // Error / signed-out mode: the one tool, `tacit_status`, and the same text on stderr (D-49, D-52).
299
+ process.stderr.write(`[TACIT] ${startup.mode.message}\n`);
300
+ registerStatusTool(server, startup.mode, startup.source, startup.profile);
301
+ await server.connect(new StdioServerTransport());
302
+ return;
354
303
  }
304
+ stdioClient = startup.client;
305
+ // The ~107 tool call sites that use the module-level getClient() share this identity.
306
+ setDefaultClient(stdioClient);
355
307
  }
356
308
  const getClient = async () => {
357
- if (isHttpMode) {
309
+ if (isHttpMode || !stdioClient) {
358
310
  return getModuleClient();
359
311
  }
360
- if (!clientInstance) {
361
- clientInstance = new TacitClient(profileOpts);
362
- await clientInstance.initialize();
363
- }
364
- return clientInstance;
312
+ return stdioClient;
365
313
  };
366
314
  // MV-1539: install preCall hook before tool registration
367
315
  installPreCallHook(server);
package/dist/oauth.d.ts CHANGED
@@ -5,7 +5,7 @@
5
5
  * and access tokens — process restart voids all grants.
6
6
  *
7
7
  * Security invariants:
8
- * - PINs, auth codes, and token values are NEVER logged.
8
+ * - passwords, auth codes, and token values are NEVER logged.
9
9
  * - OAuth path NEVER falls back to process.env.TACIT_TOKEN.
10
10
  * - Unknown client_id → 400 (never redirect to unregistered URI).
11
11
  * - code_challenge_method must be S256 (plain rejected).
package/dist/oauth.js CHANGED
@@ -5,7 +5,7 @@
5
5
  * and access tokens — process restart voids all grants.
6
6
  *
7
7
  * Security invariants:
8
- * - PINs, auth codes, and token values are NEVER logged.
8
+ * - passwords, auth codes, and token values are NEVER logged.
9
9
  * - OAuth path NEVER falls back to process.env.TACIT_TOKEN.
10
10
  * - Unknown client_id → 400 (never redirect to unregistered URI).
11
11
  * - code_challenge_method must be S256 (plain rejected).
@@ -274,8 +274,8 @@ ${errorHtml}
274
274
  <input type="hidden" name="csrf_token" value="${escapeHtml(params.csrf_token)}">
275
275
  <label for="email">Email</label>
276
276
  <input id="email" name="email" type="email" required autocomplete="email">
277
- <label for="pin">PIN</label>
278
- <input id="pin" name="pin" type="password" required autocomplete="current-password" inputmode="numeric">
277
+ <label for="pin">Password</label>
278
+ <input id="pin" name="pin" type="password" required autocomplete="current-password">
279
279
  <button type="submit">Authorize</button>
280
280
  </form>
281
281
  </div>
@@ -400,7 +400,7 @@ export async function handleAuthorizePost(req, res, apiUrl) {
400
400
  sendHtmlResponse(res, 400, renderLoginPage({
401
401
  client_name: client?.client_name ?? 'Unknown',
402
402
  csrf_token: newCsrf,
403
- error: 'Email and PIN are required',
403
+ error: 'Email and password are required',
404
404
  }));
405
405
  return;
406
406
  }
@@ -426,7 +426,7 @@ export async function handleAuthorizePost(req, res, apiUrl) {
426
426
  sendHtmlResponse(res, 401, renderLoginPage({
427
427
  client_name: client?.client_name ?? 'Unknown',
428
428
  csrf_token: newCsrf,
429
- error: 'Invalid email or PIN',
429
+ error: 'Invalid email or password',
430
430
  }));
431
431
  return;
432
432
  }