@tacitai/mcp-server 0.7.0 → 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.
- package/dist/api-errors.d.ts +102 -0
- package/dist/api-errors.js +165 -0
- package/dist/autonomy.d.ts +46 -0
- package/dist/autonomy.js +118 -0
- package/dist/claude-config.d.ts +139 -0
- package/dist/claude-config.js +339 -0
- package/dist/cli-launch.d.ts +33 -0
- package/dist/cli-launch.js +178 -0
- package/dist/cli-login.d.ts +34 -0
- package/dist/cli-login.js +200 -0
- package/dist/cli-mode.d.ts +47 -0
- package/dist/cli-mode.js +170 -0
- package/dist/cli-profiles.d.ts +37 -0
- package/dist/cli-profiles.js +344 -0
- package/dist/cli.d.ts +9 -0
- package/dist/cli.js +59 -458
- package/dist/client.d.ts +88 -52
- package/dist/client.js +195 -295
- package/dist/credentials.d.ts +81 -0
- package/dist/credentials.js +291 -0
- package/dist/index.d.ts +3 -3
- package/dist/index.js +37 -89
- package/dist/oauth.d.ts +1 -1
- package/dist/oauth.js +5 -5
- package/dist/profile-store.d.ts +96 -0
- package/dist/profile-store.js +382 -0
- package/dist/prompt.d.ts +32 -0
- package/dist/prompt.js +99 -0
- package/dist/prompts.d.ts +2 -2
- package/dist/prompts.js +3 -3
- package/dist/server-mode.d.ts +65 -0
- package/dist/server-mode.js +99 -0
- package/dist/setup-migrate.d.ts +35 -0
- package/dist/setup-migrate.js +204 -0
- package/dist/setup.d.ts +41 -66
- package/dist/setup.js +361 -531
- package/dist/signin.d.ts +108 -0
- package/dist/signin.js +595 -0
- package/dist/tools/agents.d.ts +4 -4
- package/dist/tools/artifacts.d.ts +2 -0
- package/dist/tools/artifacts.js +8 -1
- package/dist/tools/errors.d.ts +12 -0
- package/dist/tools/errors.js +65 -0
- package/dist/tools/exec-route.d.ts +34 -0
- package/dist/tools/exec-route.js +101 -27
- package/dist/tools/iam.js +2 -3
- package/dist/tools/secretary.d.ts +1 -0
- package/dist/tools/secretary.js +2 -1
- package/dist/tools/synthesize.d.ts +37 -0
- package/dist/tools/synthesize.js +126 -7
- package/dist/tools/voice.d.ts +3 -2
- package/dist/tools/voice.js +70 -18
- package/dist/tools/workspaces.js +7 -4
- package/dist/version.d.ts +6 -0
- package/dist/version.js +18 -0
- package/dist/workflow-registry.d.ts +1 -0
- package/dist/workflow-registry.js +21 -0
- package/package.json +4 -1
package/dist/client.js
CHANGED
|
@@ -1,35 +1,44 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* TacitClient — REST/SSE client over
|
|
2
|
+
* TacitClient — REST/SSE client over an API URL it is GIVEN.
|
|
3
3
|
*
|
|
4
4
|
* Security invariants (enforced here and NEVER relaxed):
|
|
5
|
-
* -
|
|
5
|
+
* - The token is NEVER written to any output stream (stdout, stderr, logs).
|
|
6
6
|
* - The Authorization header value is NEVER logged at any level.
|
|
7
7
|
* - No anthropic/openai SDK import.
|
|
8
|
-
* -
|
|
8
|
+
* - This module reads no credential from the environment. Credentials arrive as
|
|
9
|
+
* constructor options from credentials.ts (levels 0/1/2/4/5), the only
|
|
10
|
+
* module that reads them (MV-1542c step 1.4).
|
|
9
11
|
*/
|
|
10
12
|
import * as fs from 'fs';
|
|
11
13
|
import * as path from 'path';
|
|
12
|
-
import * as os from 'os';
|
|
13
14
|
import { AsyncLocalStorage } from 'node:async_hooks';
|
|
15
|
+
import { clearAutonomyCache } from './autonomy.js';
|
|
16
|
+
import { messageForResponse, SWITCH_NOT_SUPPORTED } from './api-errors.js';
|
|
17
|
+
// Autonomy lives in autonomy.ts; re-exported so existing importers keep working.
|
|
18
|
+
export { parseAutonomyLevel, autonomyAtLeast, getCachedAutonomy, ensureAutonomy, } from './autonomy.js';
|
|
14
19
|
function isHmacSessionToken(token) {
|
|
15
20
|
const parts = token.split('.');
|
|
16
21
|
return parts.length === 2 && /^[0-9a-f]{64}$/.test(parts[1]);
|
|
17
22
|
}
|
|
23
|
+
const JWT_SHAPE_RE = /^eyJ[A-Za-z0-9_-]*\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]*$/;
|
|
24
|
+
/** Default API URL when a caller supplies none. Only level-2 env credentials and tests rely on it. */
|
|
25
|
+
const FALLBACK_API_URL = 'http://localhost:7473';
|
|
18
26
|
export class TacitClient {
|
|
19
27
|
apiUrl;
|
|
20
28
|
_appUrl;
|
|
21
29
|
token;
|
|
30
|
+
sessionToken;
|
|
22
31
|
_fetch;
|
|
23
32
|
_rootDir;
|
|
24
33
|
_workspaceId;
|
|
25
|
-
_workspaceName
|
|
34
|
+
_workspaceName;
|
|
35
|
+
_credentialSource;
|
|
36
|
+
_envVar;
|
|
26
37
|
_initialized = false;
|
|
27
38
|
/**
|
|
28
|
-
* @param fetchOrOpts -
|
|
29
|
-
*
|
|
30
|
-
*
|
|
31
|
-
* @param opts - Additional options (apiUrl, token, workspaceId, rootDir).
|
|
32
|
-
* Only used when fetchOrOpts is a fetch function.
|
|
39
|
+
* @param fetchOrOpts - A custom fetch implementation (for testing) or a
|
|
40
|
+
* TacitClientOptions object.
|
|
41
|
+
* @param opts - Options when the first argument is a fetch function.
|
|
33
42
|
*/
|
|
34
43
|
constructor(fetchOrOpts, opts = {}) {
|
|
35
44
|
let resolvedOpts = {};
|
|
@@ -42,13 +51,17 @@ export class TacitClient {
|
|
|
42
51
|
resolvedOpts = fetchOrOpts;
|
|
43
52
|
this._fetch = globalThis.fetch.bind(globalThis);
|
|
44
53
|
}
|
|
45
|
-
this.apiUrl = (resolvedOpts.apiUrl ??
|
|
46
|
-
this._appUrl = (resolvedOpts.appUrl ??
|
|
47
|
-
//
|
|
48
|
-
this.token = resolvedOpts.token ??
|
|
54
|
+
this.apiUrl = (resolvedOpts.apiUrl ?? FALLBACK_API_URL).replace(/\/$/, '');
|
|
55
|
+
this._appUrl = (resolvedOpts.appUrl ?? '').replace(/\/$/, '');
|
|
56
|
+
// NEVER log these values.
|
|
57
|
+
this.token = resolvedOpts.token ?? '';
|
|
58
|
+
this.sessionToken = resolvedOpts.sessionToken ?? '';
|
|
49
59
|
this._rootDir = resolvedOpts.rootDir ?? process.cwd();
|
|
50
|
-
|
|
51
|
-
|
|
60
|
+
this._workspaceName = resolvedOpts.workspaceName ?? null;
|
|
61
|
+
this._credentialSource = resolvedOpts.credentialSource ?? 'profile';
|
|
62
|
+
this._envVar = resolvedOpts.envVar ?? null;
|
|
63
|
+
let resolvedWorkspaceId = resolvedOpts.workspaceId ?? '';
|
|
64
|
+
// BUG-369: sync.json is a FALLBACK, not an override. Only used when no workspace id was supplied.
|
|
52
65
|
if (!resolvedWorkspaceId) {
|
|
53
66
|
try {
|
|
54
67
|
const syncPath = path.join(this._rootDir, '.tacit', 'sync.json');
|
|
@@ -65,35 +78,71 @@ export class TacitClient {
|
|
|
65
78
|
}
|
|
66
79
|
this._workspaceId = resolvedWorkspaceId;
|
|
67
80
|
}
|
|
81
|
+
/** Values that fill the `<workspace>` / credential slots of api-errors.ts messages. */
|
|
82
|
+
errorContext() {
|
|
83
|
+
return { workspace: this._workspaceName, credentialSource: this._credentialSource, envVar: this._envVar };
|
|
84
|
+
}
|
|
68
85
|
get workspaceId() {
|
|
69
86
|
return this._workspaceId;
|
|
70
87
|
}
|
|
71
88
|
get workspaceName() {
|
|
72
89
|
return this._workspaceName;
|
|
73
90
|
}
|
|
91
|
+
/** GET /api/v1/auth/whoami. Throws TokenExpiredError (401) or TacitApiError. */
|
|
92
|
+
async whoami(timeoutMs = 10_000) {
|
|
93
|
+
return this.get('/api/v1/auth/whoami', undefined, timeoutMs);
|
|
94
|
+
}
|
|
95
|
+
/** Adopt a verified identity: fills a missing workspace id and the name; skips the /workspaces/mine lookup. */
|
|
96
|
+
applyIdentity(who) {
|
|
97
|
+
if (!this._workspaceId)
|
|
98
|
+
this._workspaceId = who.workspace_id;
|
|
99
|
+
if (who.workspace_name)
|
|
100
|
+
this._workspaceName = who.workspace_name;
|
|
101
|
+
this._initialized = true;
|
|
102
|
+
}
|
|
103
|
+
/**
|
|
104
|
+
* Decoded payload of an HMAC session credential (carries the autonomy claim), or null
|
|
105
|
+
* when the client does not hold one. Never returns the token itself.
|
|
106
|
+
*/
|
|
107
|
+
hmacSessionClaims() {
|
|
108
|
+
const hmac = this.sessionToken || (isHmacSessionToken(this.token) ? this.token : '');
|
|
109
|
+
if (!hmac)
|
|
110
|
+
return null;
|
|
111
|
+
try {
|
|
112
|
+
const payload = JSON.parse(Buffer.from(hmac.split('.')[0], 'base64url').toString('utf-8'));
|
|
113
|
+
return payload && typeof payload === 'object' ? payload : null;
|
|
114
|
+
}
|
|
115
|
+
catch {
|
|
116
|
+
return null;
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
/**
|
|
120
|
+
* Fill in the workspace name for a client built without one (level-2 env credentials on an
|
|
121
|
+
* old server). Never replaces a workspace id that is already set.
|
|
122
|
+
*/
|
|
74
123
|
async initialize() {
|
|
75
124
|
if (this._initialized)
|
|
76
125
|
return;
|
|
126
|
+
if (this._workspaceId && this._workspaceName) {
|
|
127
|
+
this._initialized = true;
|
|
128
|
+
return;
|
|
129
|
+
}
|
|
77
130
|
try {
|
|
78
131
|
const data = await this.get('/api/v1/workspaces/mine');
|
|
79
132
|
if (data && typeof data === 'object') {
|
|
80
|
-
if (
|
|
133
|
+
if (!this._workspaceId && typeof data.active_workspace_id === 'string') {
|
|
81
134
|
this._workspaceId = data.active_workspace_id;
|
|
82
135
|
}
|
|
83
136
|
if (Array.isArray(data.workspaces) && data.workspaces.length > 0) {
|
|
84
|
-
const
|
|
137
|
+
const list = data.workspaces;
|
|
138
|
+
const active = list.find((w) => (w.workspace_id ?? w.id) === this._workspaceId) ?? (this._workspaceId ? undefined : list[0]);
|
|
85
139
|
if (active) {
|
|
140
|
+
if (!this._workspaceId)
|
|
141
|
+
this._workspaceId = (active.workspace_id ?? active.id);
|
|
86
142
|
const name = active.display_name ?? active.name;
|
|
87
143
|
if (typeof name === 'string')
|
|
88
144
|
this._workspaceName = name;
|
|
89
145
|
}
|
|
90
|
-
if (!this._workspaceId) {
|
|
91
|
-
const first = data.workspaces[0];
|
|
92
|
-
this._workspaceId = (first.workspace_id ?? first.id);
|
|
93
|
-
const name = first.display_name ?? first.name;
|
|
94
|
-
if (typeof name === 'string')
|
|
95
|
-
this._workspaceName = name;
|
|
96
|
-
}
|
|
97
146
|
}
|
|
98
147
|
}
|
|
99
148
|
this._initialized = true;
|
|
@@ -102,39 +151,37 @@ export class TacitClient {
|
|
|
102
151
|
this._initialized = true;
|
|
103
152
|
}
|
|
104
153
|
}
|
|
154
|
+
/**
|
|
155
|
+
* Switch workspace. Session JWT credentials only (G4, D-45): any other credential kind
|
|
156
|
+
* switches by choosing another saved login, so it gets a named error instead of a 401.
|
|
157
|
+
*/
|
|
105
158
|
async switchWorkspace(workspaceId) {
|
|
159
|
+
if (!JWT_SHAPE_RE.test(this.token))
|
|
160
|
+
throw new SwitchNotSupportedError();
|
|
106
161
|
const data = await this.post('/api/v1/auth/switch-workspace', {
|
|
107
162
|
workspace_id: workspaceId,
|
|
108
163
|
});
|
|
109
|
-
if (data
|
|
110
|
-
|
|
111
|
-
}
|
|
112
|
-
this._workspaceId = workspaceId;
|
|
113
|
-
if (data && typeof data === 'object' && 'name' in data && typeof data.name === 'string') {
|
|
114
|
-
this._workspaceName = data.name;
|
|
115
|
-
}
|
|
116
|
-
else {
|
|
117
|
-
this._workspaceName = null;
|
|
164
|
+
if (!data || typeof data !== 'object' || typeof data['session_token'] !== 'string') {
|
|
165
|
+
throw new Error('TACIT returned no session token for the workspace switch.');
|
|
118
166
|
}
|
|
167
|
+
this.token = data['session_token'];
|
|
168
|
+
this._workspaceId = typeof data['workspace_id'] === 'string' ? data['workspace_id'] : workspaceId;
|
|
169
|
+
this._workspaceName = typeof data['workspace_name'] === 'string' ? data['workspace_name'] : null;
|
|
170
|
+
clearAutonomyCache();
|
|
119
171
|
return {
|
|
120
|
-
workspace_id:
|
|
172
|
+
workspace_id: this._workspaceId,
|
|
121
173
|
name: this._workspaceName ?? 'unknown',
|
|
122
174
|
};
|
|
123
175
|
}
|
|
124
176
|
/**
|
|
125
177
|
* Resolve the workspace ID:
|
|
126
|
-
* 1. Return this._workspaceId if already set (
|
|
127
|
-
* 2.
|
|
128
|
-
* 3.
|
|
129
|
-
* 4. Return null if no source is available.
|
|
178
|
+
* 1. Return this._workspaceId if already set (constructor options / profile / whoami).
|
|
179
|
+
* 2. Fall back to <rootDir>/.tacit/sync.json.
|
|
180
|
+
* 3. Return null if no source is available.
|
|
130
181
|
*/
|
|
131
182
|
async resolveWorkspaceId() {
|
|
132
183
|
if (this._workspaceId)
|
|
133
184
|
return this._workspaceId;
|
|
134
|
-
// BUG-369: env takes precedence over sync.json
|
|
135
|
-
const envId = process.env['TACIT_WORKSPACE_ID'];
|
|
136
|
-
if (envId && envId.length > 0)
|
|
137
|
-
return envId;
|
|
138
185
|
try {
|
|
139
186
|
const syncPath = path.join(this._rootDir, '.tacit', 'sync.json');
|
|
140
187
|
if (fs.existsSync(syncPath)) {
|
|
@@ -151,7 +198,7 @@ export class TacitClient {
|
|
|
151
198
|
}
|
|
152
199
|
/**
|
|
153
200
|
* Build a user-facing URL for an entity in the TACIT web app.
|
|
154
|
-
* Returns null when
|
|
201
|
+
* Returns null when no app URL is configured.
|
|
155
202
|
*
|
|
156
203
|
* Route patterns (TanStack file-based routing in tacitai.app.beta):
|
|
157
204
|
* artifact → /view/:id
|
|
@@ -190,19 +237,15 @@ export class TacitClient {
|
|
|
190
237
|
/**
|
|
191
238
|
* Build auth headers. Value is NEVER written to logs.
|
|
192
239
|
*
|
|
193
|
-
* MV-1515n
|
|
194
|
-
* X-Tacit-Session
|
|
195
|
-
* format), it takes precedence and is sent as X-Tacit-Session instead of
|
|
196
|
-
* Authorization — this is additive and does not change default behavior
|
|
197
|
-
* (Bearer via TACIT_TOKEN) when TACIT_SESSION_TOKEN is unset.
|
|
240
|
+
* An HMAC session credential (explicit `sessionToken`, MV-1515n harness, or an HMAC-shaped
|
|
241
|
+
* token) is sent as X-Tacit-Session; everything else as a Bearer token.
|
|
198
242
|
*/
|
|
199
243
|
authHeaders(extra) {
|
|
200
244
|
const headers = {
|
|
201
245
|
'Content-Type': 'application/json',
|
|
202
246
|
};
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
headers['X-Tacit-Session'] = sessionToken;
|
|
247
|
+
if (this.sessionToken) {
|
|
248
|
+
headers['X-Tacit-Session'] = this.sessionToken;
|
|
206
249
|
}
|
|
207
250
|
else if (this.token) {
|
|
208
251
|
if (isHmacSessionToken(this.token)) {
|
|
@@ -216,8 +259,24 @@ export class TacitClient {
|
|
|
216
259
|
Object.assign(headers, extra);
|
|
217
260
|
return headers;
|
|
218
261
|
}
|
|
262
|
+
/**
|
|
263
|
+
* Every request carries a credential, so none may follow a redirect (L-7): a 307/308 would re-send
|
|
264
|
+
* the Authorization / X-Tacit-Session header and body to another origin. A 3xx is an error.
|
|
265
|
+
*/
|
|
266
|
+
async send(url, init) {
|
|
267
|
+
const res = await this._fetch(url, { ...init, redirect: 'manual' });
|
|
268
|
+
if (res.status >= 300 && res.status < 400) {
|
|
269
|
+
let host = url;
|
|
270
|
+
try {
|
|
271
|
+
host = new URL(url).host;
|
|
272
|
+
}
|
|
273
|
+
catch { /* keep raw */ }
|
|
274
|
+
throw new TacitApiError(res.status, `${host} answered with a redirect (HTTP ${res.status}). TACIT does not follow redirects with a login attached.`, new URL(url, 'http://x').pathname);
|
|
275
|
+
}
|
|
276
|
+
return res;
|
|
277
|
+
}
|
|
219
278
|
/** GET request returning parsed JSON. */
|
|
220
|
-
async get(endpoint, params) {
|
|
279
|
+
async get(endpoint, params, timeoutMs) {
|
|
221
280
|
const url = new URL(`${this.apiUrl}${endpoint}`);
|
|
222
281
|
if (params) {
|
|
223
282
|
for (const [k, v] of Object.entries(params)) {
|
|
@@ -225,17 +284,12 @@ export class TacitClient {
|
|
|
225
284
|
url.searchParams.set(k, String(v));
|
|
226
285
|
}
|
|
227
286
|
}
|
|
228
|
-
const
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
if (!res.ok)
|
|
233
|
-
|
|
234
|
-
if (res.status === 401) {
|
|
235
|
-
throw new TokenExpiredError(`${this.apiUrl}/settings`, `npx @tacitai/mcp-server setup --api-url ${this.apiUrl}`);
|
|
236
|
-
}
|
|
237
|
-
throw new TacitApiError(res.status, body, endpoint);
|
|
238
|
-
}
|
|
287
|
+
const init = { method: 'GET', headers: this.authHeaders() };
|
|
288
|
+
if (timeoutMs)
|
|
289
|
+
init.signal = AbortSignal.timeout(timeoutMs);
|
|
290
|
+
const res = await this.send(url.toString(), init);
|
|
291
|
+
if (!res.ok)
|
|
292
|
+
await throwForStatus(res, endpoint, this.apiUrl, this.errorContext());
|
|
239
293
|
return res.json();
|
|
240
294
|
}
|
|
241
295
|
/** POST request returning parsed JSON. `extraHeaders` merges on top of auth headers (e.g. If-Match). */
|
|
@@ -247,45 +301,30 @@ export class TacitClient {
|
|
|
247
301
|
};
|
|
248
302
|
if (timeoutMs)
|
|
249
303
|
opts.signal = AbortSignal.timeout(timeoutMs);
|
|
250
|
-
const res = await this.
|
|
251
|
-
if (!res.ok)
|
|
252
|
-
|
|
253
|
-
if (res.status === 401) {
|
|
254
|
-
throw new TokenExpiredError(`${this.apiUrl}/settings`, `npx @tacitai/mcp-server setup --api-url ${this.apiUrl}`);
|
|
255
|
-
}
|
|
256
|
-
throw new TacitApiError(res.status, text, endpoint);
|
|
257
|
-
}
|
|
304
|
+
const res = await this.send(`${this.apiUrl}${endpoint}`, opts);
|
|
305
|
+
if (!res.ok)
|
|
306
|
+
await throwForStatus(res, endpoint, this.apiUrl, this.errorContext());
|
|
258
307
|
return res.json();
|
|
259
308
|
}
|
|
260
309
|
/** PUT request returning parsed JSON. */
|
|
261
310
|
async put(endpoint, body) {
|
|
262
|
-
const res = await this.
|
|
311
|
+
const res = await this.send(`${this.apiUrl}${endpoint}`, {
|
|
263
312
|
method: 'PUT',
|
|
264
313
|
headers: this.authHeaders(),
|
|
265
314
|
body: JSON.stringify(body),
|
|
266
315
|
});
|
|
267
|
-
if (!res.ok)
|
|
268
|
-
|
|
269
|
-
if (res.status === 401) {
|
|
270
|
-
throw new TokenExpiredError(`${this.apiUrl}/settings`, `npx @tacitai/mcp-server setup --api-url ${this.apiUrl}`);
|
|
271
|
-
}
|
|
272
|
-
throw new TacitApiError(res.status, text, endpoint);
|
|
273
|
-
}
|
|
316
|
+
if (!res.ok)
|
|
317
|
+
await throwForStatus(res, endpoint, this.apiUrl, this.errorContext());
|
|
274
318
|
return res.json();
|
|
275
319
|
}
|
|
276
320
|
/** DELETE request returning parsed JSON (or empty on 204). */
|
|
277
321
|
async delete(endpoint) {
|
|
278
|
-
const res = await this.
|
|
322
|
+
const res = await this.send(`${this.apiUrl}${endpoint}`, {
|
|
279
323
|
method: 'DELETE',
|
|
280
324
|
headers: this.authHeaders(),
|
|
281
325
|
});
|
|
282
|
-
if (!res.ok)
|
|
283
|
-
|
|
284
|
-
if (res.status === 401) {
|
|
285
|
-
throw new TokenExpiredError(`${this.apiUrl}/settings`, `npx @tacitai/mcp-server setup --api-url ${this.apiUrl}`);
|
|
286
|
-
}
|
|
287
|
-
throw new TacitApiError(res.status, text, endpoint);
|
|
288
|
-
}
|
|
326
|
+
if (!res.ok)
|
|
327
|
+
await throwForStatus(res, endpoint, this.apiUrl, this.errorContext());
|
|
289
328
|
if (res.status === 204)
|
|
290
329
|
return null;
|
|
291
330
|
return res.json();
|
|
@@ -302,18 +341,13 @@ export class TacitClient {
|
|
|
302
341
|
}
|
|
303
342
|
/** PATCH request returning parsed JSON. */
|
|
304
343
|
async patch(endpoint, body) {
|
|
305
|
-
const res = await this.
|
|
344
|
+
const res = await this.send(`${this.apiUrl}${endpoint}`, {
|
|
306
345
|
method: 'PATCH',
|
|
307
346
|
headers: this.authHeaders(),
|
|
308
347
|
body: JSON.stringify(body),
|
|
309
348
|
});
|
|
310
|
-
if (!res.ok)
|
|
311
|
-
|
|
312
|
-
if (res.status === 401) {
|
|
313
|
-
throw new TokenExpiredError(`${this.apiUrl}/settings`, `npx @tacitai/mcp-server setup --api-url ${this.apiUrl}`);
|
|
314
|
-
}
|
|
315
|
-
throw new TacitApiError(res.status, text, endpoint);
|
|
316
|
-
}
|
|
349
|
+
if (!res.ok)
|
|
350
|
+
await throwForStatus(res, endpoint, this.apiUrl, this.errorContext());
|
|
317
351
|
if (res.status === 204) {
|
|
318
352
|
return {};
|
|
319
353
|
}
|
|
@@ -324,7 +358,7 @@ export class TacitClient {
|
|
|
324
358
|
* The Authorization header value is never written to process.stderr or stdout.
|
|
325
359
|
*/
|
|
326
360
|
async *postSSE(endpoint, body) {
|
|
327
|
-
const res = await this.
|
|
361
|
+
const res = await this.send(`${this.apiUrl}${endpoint}`, {
|
|
328
362
|
method: 'POST',
|
|
329
363
|
headers: {
|
|
330
364
|
...this.authHeaders(),
|
|
@@ -332,13 +366,8 @@ export class TacitClient {
|
|
|
332
366
|
},
|
|
333
367
|
body: JSON.stringify(body),
|
|
334
368
|
});
|
|
335
|
-
if (!res.ok)
|
|
336
|
-
|
|
337
|
-
if (res.status === 401) {
|
|
338
|
-
throw new TokenExpiredError(`${this.apiUrl}/settings`, `npx @tacitai/mcp-server setup --api-url ${this.apiUrl}`);
|
|
339
|
-
}
|
|
340
|
-
throw new TacitApiError(res.status, text, endpoint);
|
|
341
|
-
}
|
|
369
|
+
if (!res.ok)
|
|
370
|
+
await throwForStatus(res, endpoint, this.apiUrl, this.errorContext());
|
|
342
371
|
if (!res.body) {
|
|
343
372
|
throw new Error('SSE response has no body');
|
|
344
373
|
}
|
|
@@ -376,23 +405,17 @@ export class TacitClient {
|
|
|
376
405
|
}
|
|
377
406
|
/** POST multipart form data (for file ingest). */
|
|
378
407
|
async postFormData(endpoint, formData) {
|
|
379
|
-
//
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
}
|
|
384
|
-
const res = await this._fetch(`${this.apiUrl}${endpoint}`, {
|
|
408
|
+
// Use authHeaders() for correct HMAC/Bearer routing (BUG-403),
|
|
409
|
+
// then drop Content-Type so fetch sets the multipart boundary.
|
|
410
|
+
const headers = this.authHeaders();
|
|
411
|
+
delete headers['Content-Type'];
|
|
412
|
+
const res = await this.send(`${this.apiUrl}${endpoint}`, {
|
|
385
413
|
method: 'POST',
|
|
386
414
|
headers,
|
|
387
415
|
body: formData,
|
|
388
416
|
});
|
|
389
|
-
if (!res.ok)
|
|
390
|
-
|
|
391
|
-
if (res.status === 401) {
|
|
392
|
-
throw new TokenExpiredError(`${this.apiUrl}/settings`, `npx @tacitai/mcp-server setup --api-url ${this.apiUrl}`);
|
|
393
|
-
}
|
|
394
|
-
throw new TacitApiError(res.status, text, endpoint);
|
|
395
|
-
}
|
|
417
|
+
if (!res.ok)
|
|
418
|
+
await throwForStatus(res, endpoint, this.apiUrl, this.errorContext());
|
|
396
419
|
return res.json();
|
|
397
420
|
}
|
|
398
421
|
}
|
|
@@ -400,29 +423,39 @@ export class TacitApiError extends Error {
|
|
|
400
423
|
statusCode;
|
|
401
424
|
body;
|
|
402
425
|
endpoint;
|
|
403
|
-
|
|
426
|
+
workspace;
|
|
427
|
+
constructor(statusCode, body, endpoint,
|
|
428
|
+
/** Workspace name when the client knew it, for the <workspace> slot of api-errors.ts messages. */
|
|
429
|
+
workspace = null) {
|
|
404
430
|
super(`Tacit API error ${statusCode} on ${endpoint}`);
|
|
405
431
|
this.statusCode = statusCode;
|
|
406
432
|
this.body = body;
|
|
407
433
|
this.endpoint = endpoint;
|
|
434
|
+
this.workspace = workspace;
|
|
408
435
|
this.name = 'TacitApiError';
|
|
409
436
|
}
|
|
410
437
|
}
|
|
411
438
|
/**
|
|
412
|
-
* Thrown when the API returns 401 —
|
|
413
|
-
*
|
|
439
|
+
* Thrown when the API returns 401 — the credential has expired or been revoked.
|
|
440
|
+
* Tools catch this and surface a user-actionable message.
|
|
414
441
|
*
|
|
415
|
-
*
|
|
416
|
-
*
|
|
417
|
-
* re-auth needed). After 7 days, full device-auth is required.
|
|
442
|
+
* `code` is the server's named error code when the 401 body carried one
|
|
443
|
+
* (e.g. MEMBERSHIP_NOT_FOUND, CREDENTIAL_BINDING_MISMATCH); null for an old server.
|
|
418
444
|
*
|
|
419
445
|
* Security invariant: token plaintext is NEVER included in this error.
|
|
420
446
|
*/
|
|
421
447
|
export class TokenExpiredError extends Error {
|
|
422
448
|
renewalUrl;
|
|
423
449
|
setupCommand;
|
|
424
|
-
|
|
425
|
-
|
|
450
|
+
code;
|
|
451
|
+
workspace;
|
|
452
|
+
statusCode = 401;
|
|
453
|
+
constructor(renewalUrl, setupCommand, code = null,
|
|
454
|
+
/** The api-errors.ts message for this 401. When absent, the generic renewal text is used. */
|
|
455
|
+
message,
|
|
456
|
+
/** Workspace name when the client knew it. */
|
|
457
|
+
workspace = null) {
|
|
458
|
+
const msg = message ?? [
|
|
426
459
|
'Developer token expired or revoked.',
|
|
427
460
|
'Re-authenticate within 7 days for easy refresh (no browser flow needed).',
|
|
428
461
|
`Renew at: ${renewalUrl}`,
|
|
@@ -431,101 +464,49 @@ export class TokenExpiredError extends Error {
|
|
|
431
464
|
super(msg);
|
|
432
465
|
this.renewalUrl = renewalUrl;
|
|
433
466
|
this.setupCommand = setupCommand;
|
|
467
|
+
this.code = code;
|
|
468
|
+
this.workspace = workspace;
|
|
434
469
|
this.name = 'TokenExpiredError';
|
|
435
470
|
}
|
|
436
471
|
}
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
if (!PROFILE_NAME_RE.test(name)) {
|
|
443
|
-
throw new Error(`Invalid profile name '${name}'. Names must match: ${PROFILE_NAME_RE}`);
|
|
444
|
-
}
|
|
445
|
-
const profilePath = path.join(os.homedir(), '.tacit', 'profiles', `${name}.json`);
|
|
446
|
-
if (!fs.existsSync(profilePath)) {
|
|
447
|
-
throw new Error(`Profile '${name}' not found at ${profilePath}`);
|
|
472
|
+
/** `tacit_switch_workspace` with a credential that is not a session JWT (D-45). */
|
|
473
|
+
export class SwitchNotSupportedError extends Error {
|
|
474
|
+
constructor() {
|
|
475
|
+
super(SWITCH_NOT_SUPPORTED);
|
|
476
|
+
this.name = 'SwitchNotSupportedError';
|
|
448
477
|
}
|
|
449
|
-
|
|
478
|
+
}
|
|
479
|
+
/** Named error code from a JSON error body: {"error":{"code":"X"}}, {"code":"X"} or {"error":"X"}. */
|
|
480
|
+
function errorCodeOf(body) {
|
|
450
481
|
try {
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
}
|
|
456
|
-
if (data.version !== 2) {
|
|
457
|
-
throw new Error(`Profile '${name}' was created by setup and lacks credentials. Re-run: npx -p @tacitai/mcp-server tacit login`);
|
|
458
|
-
}
|
|
459
|
-
if (typeof data.workspace_id !== 'string' || !data.workspace_id ||
|
|
460
|
-
typeof data.token !== 'string' || !data.token ||
|
|
461
|
-
typeof data.api_url !== 'string' || !data.api_url) {
|
|
462
|
-
throw new Error(`Profile '${name}' is missing required fields (workspace_id, token, api_url). Re-run: tacit login`);
|
|
463
|
-
}
|
|
464
|
-
if (typeof data.expires_at === 'string') {
|
|
465
|
-
const expiresMs = Date.parse(data.expires_at);
|
|
466
|
-
if (!Number.isNaN(expiresMs) && Date.now() > expiresMs) {
|
|
467
|
-
process.stderr.write(`[TACIT] Warning: profile '${name}' token expired ${data.expires_at}. Re-run: tacit login\n`);
|
|
482
|
+
const parsed = JSON.parse(body);
|
|
483
|
+
const nested = parsed.error;
|
|
484
|
+
if (nested && typeof nested === 'object' && typeof nested.code === 'string') {
|
|
485
|
+
return nested.code;
|
|
468
486
|
}
|
|
487
|
+
if (typeof parsed.code === 'string')
|
|
488
|
+
return parsed.code;
|
|
489
|
+
if (typeof nested === 'string')
|
|
490
|
+
return nested;
|
|
491
|
+
}
|
|
492
|
+
catch {
|
|
493
|
+
// Not JSON.
|
|
469
494
|
}
|
|
470
|
-
return
|
|
495
|
+
return null;
|
|
471
496
|
}
|
|
472
497
|
/**
|
|
473
|
-
*
|
|
474
|
-
*
|
|
475
|
-
* Throws on set-but-invalid states (profile missing, WORKSPACE_ID without TOKEN).
|
|
498
|
+
* The one place a non-2xx response becomes an error: 401 -> TokenExpiredError, anything else -> TacitApiError.
|
|
499
|
+
* The 401 message comes from api-errors.ts (named code first, then the no-code row).
|
|
476
500
|
*/
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
const
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
workspaceId: profile.workspace_id,
|
|
487
|
-
};
|
|
488
|
-
}
|
|
489
|
-
// Level 2: explicit env vars (backward compat)
|
|
490
|
-
if (isNonEmpty(process.env['TACIT_WORKSPACE_ID'])) {
|
|
491
|
-
if (!isNonEmpty(process.env['TACIT_TOKEN'])) {
|
|
492
|
-
throw new Error('TACIT_WORKSPACE_ID set but TACIT_TOKEN missing');
|
|
493
|
-
}
|
|
494
|
-
return {
|
|
495
|
-
apiUrl: process.env['TACIT_API_URL']?.trim() || undefined,
|
|
496
|
-
token: process.env['TACIT_TOKEN'].trim(),
|
|
497
|
-
workspaceId: process.env['TACIT_WORKSPACE_ID'].trim(),
|
|
498
|
-
};
|
|
499
|
-
}
|
|
500
|
-
if (isNonEmpty(process.env['TACIT_TOKEN'])) {
|
|
501
|
-
return {
|
|
502
|
-
apiUrl: process.env['TACIT_API_URL']?.trim() || undefined,
|
|
503
|
-
token: process.env['TACIT_TOKEN'].trim(),
|
|
504
|
-
};
|
|
505
|
-
}
|
|
506
|
-
// Level 3: sync.json workspace_id + default profile credentials
|
|
507
|
-
// (constructor handles sync.json as fallback when no profile opts are set)
|
|
508
|
-
// Level 4: ~/.tacit/default → profile name
|
|
509
|
-
const defaultPath = path.join(os.homedir(), '.tacit', 'default');
|
|
510
|
-
try {
|
|
511
|
-
if (fs.existsSync(defaultPath)) {
|
|
512
|
-
const defaultName = fs.readFileSync(defaultPath, 'utf-8').trim();
|
|
513
|
-
if (defaultName) {
|
|
514
|
-
const profile = loadProfile(defaultName);
|
|
515
|
-
return {
|
|
516
|
-
apiUrl: isNonEmpty(process.env['TACIT_API_URL']) ? process.env['TACIT_API_URL'].trim() : profile.api_url,
|
|
517
|
-
appUrl: isNonEmpty(process.env['TACIT_APP_URL']) ? process.env['TACIT_APP_URL'].trim() : profile.app_url,
|
|
518
|
-
token: profile.token,
|
|
519
|
-
workspaceId: profile.workspace_id,
|
|
520
|
-
};
|
|
521
|
-
}
|
|
522
|
-
}
|
|
523
|
-
}
|
|
524
|
-
catch (err) {
|
|
525
|
-
process.stderr.write(`[TACIT] Default profile load failed: ${err instanceof Error ? err.message : String(err)}\n`);
|
|
526
|
-
}
|
|
527
|
-
// Level 5: no profile config — return empty (backward compat with env-only setup)
|
|
528
|
-
return {};
|
|
501
|
+
async function throwForStatus(res, endpoint, apiUrl, ctx = {}) {
|
|
502
|
+
const text = await res.text().catch(() => '');
|
|
503
|
+
const code = errorCodeOf(text);
|
|
504
|
+
const workspace = ctx.workspace ?? null;
|
|
505
|
+
if (res.status === 401) {
|
|
506
|
+
const message = messageForResponse(401, code, ctx) ?? messageForResponse(401, null, ctx) ?? undefined;
|
|
507
|
+
throw new TokenExpiredError(`${apiUrl}/settings`, `npx @tacitai/mcp-server setup --api-url ${apiUrl}`, code, message, workspace);
|
|
508
|
+
}
|
|
509
|
+
throw new TacitApiError(res.status, text, endpoint, workspace);
|
|
529
510
|
}
|
|
530
511
|
const requestStore = new AsyncLocalStorage();
|
|
531
512
|
/** HTTPS mode: bind the caller's token/apiUrl/principal to everything run inside fn. */
|
|
@@ -535,92 +516,11 @@ export function runWithRequestContext(token, apiUrl, fn, principal) {
|
|
|
535
516
|
export function getRequestPrincipal() {
|
|
536
517
|
return requestStore.getStore()?.principal ?? null;
|
|
537
518
|
}
|
|
538
|
-
|
|
539
|
-
export function parseAutonomyLevel(raw) {
|
|
540
|
-
if (typeof raw !== 'string' || !raw)
|
|
541
|
-
return 'SCRIBE';
|
|
542
|
-
const upper = raw.toUpperCase();
|
|
543
|
-
if (upper === 'OWNER')
|
|
544
|
-
return 'TWIN';
|
|
545
|
-
if (upper === 'GUEST' || upper === 'SCRIBE' || upper === 'MENTAT' || upper === 'TWIN')
|
|
546
|
-
return upper;
|
|
547
|
-
return 'SCRIBE';
|
|
548
|
-
}
|
|
549
|
-
export function autonomyAtLeast(current, required) {
|
|
550
|
-
return AUTONOMY_ORDINAL[current] >= AUTONOMY_ORDINAL[required];
|
|
551
|
-
}
|
|
552
|
-
const autonomyCache = new Map();
|
|
553
|
-
function envFallbackAutonomy() {
|
|
554
|
-
return parseAutonomyLevel(process.env['TACIT_AUTONOMY_LEVEL']);
|
|
555
|
-
}
|
|
556
|
-
export async function getRequestAutonomy(principal) {
|
|
557
|
-
const cached = autonomyCache.get(principal);
|
|
558
|
-
if (cached)
|
|
559
|
-
return cached;
|
|
560
|
-
const token = process.env['TACIT_TOKEN'] ?? '';
|
|
561
|
-
if (!token) {
|
|
562
|
-
const level = envFallbackAutonomy();
|
|
563
|
-
autonomyCache.set(principal, level);
|
|
564
|
-
return level;
|
|
565
|
-
}
|
|
566
|
-
// HMAC session tokens carry autonomy_level in their payload — no API call needed
|
|
567
|
-
if (isHmacSessionToken(token)) {
|
|
568
|
-
try {
|
|
569
|
-
const payloadB64 = token.split('.')[0];
|
|
570
|
-
const payload = JSON.parse(Buffer.from(payloadB64, 'base64url').toString('utf-8'));
|
|
571
|
-
const level = parseAutonomyLevel(payload.autonomy_level);
|
|
572
|
-
autonomyCache.set(principal, level);
|
|
573
|
-
return level;
|
|
574
|
-
}
|
|
575
|
-
catch {
|
|
576
|
-
return envFallbackAutonomy();
|
|
577
|
-
}
|
|
578
|
-
}
|
|
579
|
-
const apiUrl = (process.env['TACIT_API_URL'] ?? 'http://localhost:7473').replace(/\/$/, '');
|
|
580
|
-
try {
|
|
581
|
-
const resp = await globalThis.fetch(`${apiUrl}/api/v1/people/myself`, {
|
|
582
|
-
headers: { Authorization: `Bearer ${token}`, Accept: 'application/json' },
|
|
583
|
-
signal: AbortSignal.timeout(5000),
|
|
584
|
-
});
|
|
585
|
-
if (resp.status === 401) {
|
|
586
|
-
return { error: 'token_expired' };
|
|
587
|
-
}
|
|
588
|
-
if (resp.status === 403) {
|
|
589
|
-
const body = await resp.text().catch(() => '');
|
|
590
|
-
if (body.includes('people.read')) {
|
|
591
|
-
autonomyCache.set(principal, 'GUEST');
|
|
592
|
-
return 'GUEST';
|
|
593
|
-
}
|
|
594
|
-
const level = envFallbackAutonomy();
|
|
595
|
-
autonomyCache.set(principal, level);
|
|
596
|
-
return level;
|
|
597
|
-
}
|
|
598
|
-
if (resp.status === 404) {
|
|
599
|
-
const level = envFallbackAutonomy();
|
|
600
|
-
autonomyCache.set(principal, level);
|
|
601
|
-
return level;
|
|
602
|
-
}
|
|
603
|
-
if (!resp.ok) {
|
|
604
|
-
const level = envFallbackAutonomy();
|
|
605
|
-
return level; // don't cache non-2xx
|
|
606
|
-
}
|
|
607
|
-
const data = (await resp.json());
|
|
608
|
-
const level = parseAutonomyLevel(data['autonomy_level']);
|
|
609
|
-
autonomyCache.set(principal, level);
|
|
610
|
-
return level;
|
|
611
|
-
}
|
|
612
|
-
catch {
|
|
613
|
-
return envFallbackAutonomy(); // network error — don't cache
|
|
614
|
-
}
|
|
615
|
-
}
|
|
616
|
-
export async function ensureAutonomy(principal) {
|
|
617
|
-
return getRequestAutonomy(principal);
|
|
618
|
-
}
|
|
619
|
-
export function getCachedAutonomy(principal) {
|
|
620
|
-
return autonomyCache.get(principal) ?? null;
|
|
621
|
-
}
|
|
622
|
-
/** Shared singleton client (initialized lazily on first use). */
|
|
519
|
+
/** Shared client for the module-level getClient() (stdio: installed once at startup by index.ts). */
|
|
623
520
|
let _defaultClient = null;
|
|
521
|
+
export function setDefaultClient(client) {
|
|
522
|
+
_defaultClient = client;
|
|
523
|
+
}
|
|
624
524
|
export function getClient() {
|
|
625
525
|
const ctx = requestStore.getStore();
|
|
626
526
|
if (ctx) {
|