@tacitai/mcp-server 0.6.55 → 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.
Files changed (59) 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 +88 -52
  18. package/dist/client.js +195 -295
  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 +4 -4
  40. package/dist/tools/artifacts.d.ts +2 -0
  41. package/dist/tools/artifacts.js +8 -1
  42. package/dist/tools/career.js +25 -1
  43. package/dist/tools/errors.d.ts +12 -0
  44. package/dist/tools/errors.js +65 -0
  45. package/dist/tools/exec-route.d.ts +34 -0
  46. package/dist/tools/exec-route.js +101 -27
  47. package/dist/tools/iam.js +2 -3
  48. package/dist/tools/secretary.d.ts +1 -0
  49. package/dist/tools/secretary.js +2 -1
  50. package/dist/tools/synthesize.d.ts +37 -0
  51. package/dist/tools/synthesize.js +126 -7
  52. package/dist/tools/voice.d.ts +3 -2
  53. package/dist/tools/voice.js +70 -18
  54. package/dist/tools/workspaces.js +7 -4
  55. package/dist/version.d.ts +6 -0
  56. package/dist/version.js +18 -0
  57. package/dist/workflow-registry.d.ts +1 -0
  58. package/dist/workflow-registry.js +21 -0
  59. package/package.json +4 -1
@@ -146,6 +146,14 @@ const addJobSchema = z.object({
146
146
  company_name: z.string().optional().describe('Company name'),
147
147
  location: z.string().optional().describe('Job location'),
148
148
  employment_type: z.string().optional().describe('Employment type (e.g. "full_time", "contract")'),
149
+ salary_min: z.number().optional().describe('Minimum salary'),
150
+ salary_max: z.number().optional().describe('Maximum salary'),
151
+ salary_currency: z.string().optional().describe('Salary currency code (e.g. "CAD", "USD")'),
152
+ remote_policy: z.string().optional().describe('Remote work policy ("remote", "hybrid", "onsite")'),
153
+ application_url: z.string().optional().describe('Direct application URL (may differ from posting URL)'),
154
+ requirements: z.string().optional().describe('Key requirements as extracted text'),
155
+ responsibilities: z.string().optional().describe('Key responsibilities as extracted text'),
156
+ notes: z.string().optional().describe('Personal notes about the job'),
149
157
  });
150
158
  const updateJobSchema = z.object({
151
159
  artifact_id: z.string().uuid().describe('Job artifact UUID'),
@@ -332,7 +340,7 @@ export function registerCareerTools(server, getClientFn) {
332
340
  }
333
341
  });
334
342
  // ── 8. tacit_career_add_job ────────────────────────────────────────────
335
- server.tool('tacit_career_add_job', 'Add a job posting to a campaign. Provide a URL (fetched and extracted), pasted text, or structured fields. job_title is always required. Deduplicates on URL — returns the existing card with duplicate:true on conflict.', addJobSchema.shape, async (args) => {
343
+ server.tool('tacit_career_add_job', 'Add a job posting to a campaign. Provide a URL (fetched and extracted), pasted text, or structured fields (salary, remote policy, application URL, requirements, responsibilities, notes). job_title is always required. Deduplicates on URL — returns the existing card with duplicate:true on conflict.', addJobSchema.shape, async (args) => {
336
344
  const blocked = flagGuard();
337
345
  if (blocked)
338
346
  return blocked;
@@ -355,6 +363,22 @@ export function registerCareerTools(server, getClientFn) {
355
363
  };
356
364
  if (input.url)
357
365
  metadata['posting_url'] = input.url;
366
+ if (input.salary_min !== undefined)
367
+ metadata['salary_min'] = input.salary_min;
368
+ if (input.salary_max !== undefined)
369
+ metadata['salary_max'] = input.salary_max;
370
+ if (input.salary_currency)
371
+ metadata['salary_currency'] = input.salary_currency;
372
+ if (input.remote_policy)
373
+ metadata['remote_policy'] = input.remote_policy;
374
+ if (input.application_url)
375
+ metadata['application_url'] = input.application_url;
376
+ if (input.requirements)
377
+ metadata['requirements'] = input.requirements;
378
+ if (input.responsibilities)
379
+ metadata['responsibilities'] = input.responsibilities;
380
+ if (input.notes)
381
+ metadata['notes'] = input.notes;
358
382
  const body = {
359
383
  title: input.job_title,
360
384
  domain: 'CAREER',
@@ -12,6 +12,18 @@ export declare function error(message: string): ToolResult & {
12
12
  export declare function featureDisabledResult(err: unknown): (ToolResult & {
13
13
  isError: true;
14
14
  }) | null;
15
+ /** The member was removed from the workspace (403 ACCOUNT_DISABLED / MEMBERSHIP_INACTIVE, 401 MEMBERSHIP_NOT_FOUND). */
16
+ export declare class AccessRemovedError extends Error {
17
+ readonly workspace: string | null;
18
+ constructor(workspace?: string | null);
19
+ }
20
+ /** Server error code from a JSON error body ({"error":{"code"}}, {"code"} or {"error":"CODE"}). */
21
+ export declare function errorCodeOfBody(body: string): string | null;
22
+ /**
23
+ * The AccessRemovedError for an API failure, or null. A removed member is a 403 with a
24
+ * removal code; a 401 MEMBERSHIP_NOT_FOUND reaches tools as TokenExpiredError with the same code.
25
+ */
26
+ export declare function accessRemovedFrom(err: unknown): AccessRemovedError | null;
15
27
  export declare function apiErrorResult(err: unknown, endpoint: string): ToolResult & {
16
28
  isError: boolean;
17
29
  };
@@ -1,4 +1,5 @@
1
1
  import { TacitApiError, TokenExpiredError } from '../client.js';
2
+ import { accessRemoved, isAccessRemovedCode, messageForResponse } from '../api-errors.js';
2
3
  export function success(data) {
3
4
  return { content: [{ type: 'text', text: JSON.stringify(data, null, 2) }] };
4
5
  }
@@ -23,6 +24,61 @@ export function featureDisabledResult(err) {
23
24
  }
24
25
  return error(`Feature disabled: ${parsed.error.message || 'unknown reason'}`);
25
26
  }
27
+ /** The member was removed from the workspace (403 ACCOUNT_DISABLED / MEMBERSHIP_INACTIVE, 401 MEMBERSHIP_NOT_FOUND). */
28
+ export class AccessRemovedError extends Error {
29
+ workspace;
30
+ constructor(workspace = null) {
31
+ super(accessRemoved({ workspace }));
32
+ this.workspace = workspace;
33
+ this.name = 'AccessRemovedError';
34
+ }
35
+ }
36
+ /** Server error code from a JSON error body ({"error":{"code"}}, {"code"} or {"error":"CODE"}). */
37
+ export function errorCodeOfBody(body) {
38
+ try {
39
+ const parsed = JSON.parse(body);
40
+ const nested = parsed.error;
41
+ if (nested && typeof nested === 'object' && typeof nested.code === 'string') {
42
+ return nested.code;
43
+ }
44
+ if (typeof parsed.code === 'string')
45
+ return parsed.code;
46
+ if (typeof nested === 'string')
47
+ return nested;
48
+ }
49
+ catch {
50
+ // Not JSON.
51
+ }
52
+ return null;
53
+ }
54
+ function reasonOfBody(body) {
55
+ try {
56
+ const parsed = JSON.parse(body);
57
+ if (typeof parsed.reason === 'string')
58
+ return parsed.reason;
59
+ const nested = parsed.error;
60
+ if (nested && typeof nested === 'object' && typeof nested.reason === 'string') {
61
+ return nested.reason;
62
+ }
63
+ }
64
+ catch {
65
+ // Not JSON.
66
+ }
67
+ return null;
68
+ }
69
+ /**
70
+ * The AccessRemovedError for an API failure, or null. A removed member is a 403 with a
71
+ * removal code; a 401 MEMBERSHIP_NOT_FOUND reaches tools as TokenExpiredError with the same code.
72
+ */
73
+ export function accessRemovedFrom(err) {
74
+ if (err instanceof TokenExpiredError) {
75
+ return isAccessRemovedCode(err.code) ? new AccessRemovedError(err.workspace) : null;
76
+ }
77
+ if (err instanceof TacitApiError && err.statusCode === 403) {
78
+ return isAccessRemovedCode(errorCodeOfBody(err.body)) ? new AccessRemovedError(err.workspace) : null;
79
+ }
80
+ return null;
81
+ }
26
82
  export function apiErrorResult(err, endpoint) {
27
83
  if (err instanceof TokenExpiredError) {
28
84
  return {
@@ -34,6 +90,15 @@ export function apiErrorResult(err, endpoint) {
34
90
  const disabled = featureDisabledResult(err);
35
91
  if (disabled)
36
92
  return disabled;
93
+ const removed = accessRemovedFrom(err);
94
+ if (removed)
95
+ return { content: [{ type: 'text', text: removed.message }], isError: true };
96
+ const mapped = messageForResponse(err.statusCode, errorCodeOfBody(err.body), {
97
+ workspace: err.workspace,
98
+ reason: reasonOfBody(err.body),
99
+ });
100
+ if (mapped)
101
+ return { content: [{ type: 'text', text: mapped }], isError: true };
37
102
  return { content: [{ type: 'text', text: `API error ${err.statusCode} on ${endpoint}: ${err.body}` }], isError: true };
38
103
  }
39
104
  const msg = err instanceof Error ? err.message : String(err);
@@ -21,6 +21,40 @@ export declare function matchRole(request: string): {
21
21
  role_slug: string;
22
22
  reason: string;
23
23
  }>;
24
+ defaulted?: boolean;
25
+ };
26
+ /** BUG-418: "in my voice" requests route to the voice_compose overlay (ADR-212). */
27
+ export declare const VOICE_INTENT_RE: RegExp;
28
+ /** The user is rewriting text they supplied, as opposed to asking for new material. */
29
+ export declare const REWRITE_INTENT_RE: RegExp;
30
+ export interface OverlayWorkflowType {
31
+ /** Must be a type registered in createDefaultRegistry (checked by verify-exec-roles.sh). */
32
+ name: string;
33
+ pattern: RegExp;
34
+ /** For these base workflow types the overlay applies only when the request is a rewrite of supplied text. */
35
+ rewriteOnlyFor?: readonly string[];
36
+ }
37
+ /** ADR-212: intent overlays. Adding one needs an amendment to the ADR. */
38
+ export declare const OVERLAY_WORKFLOW_TYPES: readonly OverlayWorkflowType[];
39
+ export interface RouteResult {
40
+ role_slug: string;
41
+ present_as: string;
42
+ workflow_type: string;
43
+ description: string;
44
+ first_tool: string;
45
+ script: string[];
46
+ alternatives?: Array<{
47
+ role_slug: string;
48
+ reason: string;
49
+ }>;
50
+ overlay_skipped?: {
51
+ overlay: string;
52
+ reason: string;
53
+ };
54
+ }
55
+ /** Pure routing: role from role_hint or matchRole; workflow_type overridden to voice_compose on voice intent. */
56
+ export declare function routeRequest(request: string, roleHint?: string): RouteResult | {
57
+ error: string;
24
58
  };
25
59
  export declare function registerExecRouteTool(server: McpServer): void;
26
60
  export {};
@@ -7,6 +7,7 @@
7
7
  * imperative next-step script the LLM can follow deterministically.
8
8
  */
9
9
  import { z } from 'zod';
10
+ import { createDefaultRegistry } from '../workflow-registry.js';
10
11
  export const ROLE_ROUTES = [
11
12
  {
12
13
  slug: 'general_manager',
@@ -134,6 +135,7 @@ export function matchRole(request) {
134
135
  return {
135
136
  primary: ROLE_ROUTES.find((r) => r.slug === 'general_manager'),
136
137
  alternatives: [],
138
+ defaulted: true,
137
139
  };
138
140
  }
139
141
  const primary = scores[0].route;
@@ -143,8 +145,68 @@ export function matchRole(request) {
143
145
  }));
144
146
  return { primary, alternatives };
145
147
  }
146
- function buildScript(role) {
148
+ /** BUG-418: "in my voice" requests route to the voice_compose overlay (ADR-212). */
149
+ export const VOICE_INTENT_RE = /\b(in my voice|in my style|my writing voice)\b/i;
150
+ /** The user is rewriting text they supplied, as opposed to asking for new material. */
151
+ export const REWRITE_INTENT_RE = /\b(rewrit\w*|rephras\w*|revis\w*|edit(s|ed|ing)?|polish\w*|redo)\b/i;
152
+ /** ADR-212: intent overlays. Adding one needs an amendment to the ADR. */
153
+ export const OVERLAY_WORKFLOW_TYPES = [
154
+ { name: 'voice_compose', pattern: VOICE_INTENT_RE, rewriteOnlyFor: ['career_application'] },
155
+ ];
156
+ const overlayRegistry = createDefaultRegistry();
157
+ /**
158
+ * ADR-212 Decision 2: a workflow type is gated if failDirection is 'closed', terminalAction is set
159
+ * (gatedChecks is declared but never read by WorkflowGate, so it gates nothing), a flat prereqs.tools list is non-empty, or any phase has approvalGate,
160
+ * gatedTools or requiredMetadata. An unregistered type is gated (fail-closed). Read from the registry.
161
+ * Returns the reason, or null when ungated.
162
+ */
163
+ function gatedReason(workflowType) {
164
+ const def = overlayRegistry.get(workflowType);
165
+ const t = `role workflow '${workflowType}'`;
166
+ const inside = "call the overlay's compose tool inside its own produce step";
167
+ if (!def)
168
+ return `${t} is not registered, so it cannot be verified as ungated (fail-closed)`;
169
+ if (def.failDirection === 'closed')
170
+ return `${t} fails closed; ${inside}`;
171
+ if (def.terminalAction)
172
+ return `${t} has a terminal action (${def.terminalAction.tool}); ${inside}`;
173
+ if (def.prereqs.kind === 'flat') {
174
+ return def.prereqs.tools.length > 0
175
+ ? `${t} requires prerequisite tools (${def.prereqs.tools.join(', ')}); ${inside}`
176
+ : null;
177
+ }
178
+ const phase = def.prereqs.phases.find((p) => p.approvalGate === true || p.gatedTools.length > 0 || p.requiredMetadata !== undefined);
179
+ return phase ? `${t} is a gated pipeline (phase '${phase.name}'); ${inside}` : null;
180
+ }
181
+ function applyOverlay(request, baseType, defaulted = false) {
182
+ for (const o of OVERLAY_WORKFLOW_TYPES) {
183
+ if (!o.pattern.test(request))
184
+ continue;
185
+ const gated = defaulted ? null : gatedReason(baseType);
186
+ if (gated)
187
+ return { skipped: { overlay: o.name, reason: gated } };
188
+ if (o.rewriteOnlyFor?.includes(baseType) && !REWRITE_INTENT_RE.test(request)) {
189
+ return { skipped: { overlay: o.name, reason: `'${baseType}' crews already apply the user's voice when generating new material; the overlay applies only to rewriting supplied text` } };
190
+ }
191
+ return { overlay: o };
192
+ }
193
+ return {};
194
+ }
195
+ function overlayFirstTool(name) {
196
+ const def = overlayRegistry.get(name);
197
+ if (def?.prereqs.kind !== 'phased')
198
+ return undefined;
199
+ return def.prereqs.phases.flatMap((p) => p.requiredTools)[0];
200
+ }
201
+ function buildScript(role, workflowType = role.workflow_type) {
147
202
  const steps = [];
203
+ if (workflowType === 'voice_compose') {
204
+ steps.push('1. Call tacit_voice_list_profiles and confirm a profile with voice_active true exists. If none exists, tell the user a voice profile needs 3+ samples and stop.');
205
+ steps.push('2. Assemble the grounded source text yourself (the draft, letter or facts to rewrite). Do not invent facts.');
206
+ steps.push('3. Call tacit_compose_in_voice with the grounded text in `content` and the instruction in `query`. Omit `content` only for KB-grounded drafts.');
207
+ steps.push('4. If the result has voice_match_degraded true, or the tool returns an error, show the user and stop for review. Never draft text yourself and claim it matches their voice.');
208
+ return steps;
209
+ }
148
210
  if (role.workflow_type === 'cto_engineering') {
149
211
  steps.push('CTO routes to the Agentic Engineering Exec. Call tacit_agent_delegate with role_slug="cto_engineer" and describe the engineering request.');
150
212
  steps.push('For new role creation: the AE Exec workflow guides through domain analysis → enforcement type selection → registration → verification.');
@@ -198,39 +260,51 @@ function buildScript(role) {
198
260
  steps.push('Check tacit_workflow_prereqs if a tool returns a workflow block — it shows required prior steps.');
199
261
  return steps;
200
262
  }
263
+ /** Pure routing: role from role_hint or matchRole; workflow_type overridden to voice_compose on voice intent. */
264
+ export function routeRequest(request, roleHint) {
265
+ let primary;
266
+ let alternatives = [];
267
+ let defaulted = false;
268
+ if (roleHint) {
269
+ const found = ROLE_ROUTES.find((r) => r.slug === roleHint);
270
+ if (!found) {
271
+ const slugs = ROLE_ROUTES.map((r) => r.slug).join(', ');
272
+ return { error: `Unknown role_hint: ${roleHint}. Available: ${slugs}` };
273
+ }
274
+ primary = found;
275
+ }
276
+ else {
277
+ const match = matchRole(request);
278
+ primary = match.primary;
279
+ alternatives = match.alternatives;
280
+ defaulted = match.defaulted === true;
281
+ }
282
+ // ADR-212 exception: no keyword matched, so GM is only the triage default, not a chosen gated role.
283
+ const { overlay, skipped } = applyOverlay(request, primary.workflow_type, defaulted);
284
+ const workflowType = overlay ? overlay.name : primary.workflow_type;
285
+ const firstTool = (overlay && overlayFirstTool(overlay.name))
286
+ || (primary.slug === 'researcher' ? 'tacit_research_prepare' : 'tacit_agent_delegate');
287
+ return {
288
+ role_slug: primary.slug,
289
+ present_as: primary.present_as,
290
+ workflow_type: workflowType,
291
+ description: primary.description,
292
+ first_tool: firstTool,
293
+ script: buildScript(primary, workflowType),
294
+ ...(skipped ? { overlay_skipped: skipped } : {}),
295
+ ...(alternatives.length > 0 ? { alternatives } : {}),
296
+ };
297
+ }
201
298
  export function registerExecRouteTool(server) {
202
299
  server.tool('tacit_exec_route', 'Route a business request to the right executive role. Returns the role, workflow type, and a step-by-step script of tools to call. Use this as the first step for any business request.', {
203
300
  request: z.string().min(1).describe('Natural language description of what you want to do'),
204
301
  role_hint: z.string().optional().describe('If you already know the role slug, pass it here to skip matching'),
205
302
  }, async (args) => {
206
303
  const { request, role_hint } = args;
207
- let primary;
208
- let alternatives = [];
209
- if (role_hint) {
210
- const found = ROLE_ROUTES.find((r) => r.slug === role_hint);
211
- if (!found) {
212
- const slugs = ROLE_ROUTES.map((r) => r.slug).join(', ');
213
- return {
214
- content: [{ type: 'text', text: JSON.stringify({ error: `Unknown role_hint: ${role_hint}. Available: ${slugs}` }) }],
215
- isError: true,
216
- };
217
- }
218
- primary = found;
304
+ const result = routeRequest(request, role_hint);
305
+ if ('error' in result) {
306
+ return { content: [{ type: 'text', text: JSON.stringify(result) }], isError: true };
219
307
  }
220
- else {
221
- const match = matchRole(request);
222
- primary = match.primary;
223
- alternatives = match.alternatives;
224
- }
225
- const result = {
226
- role_slug: primary.slug,
227
- present_as: primary.present_as,
228
- workflow_type: primary.workflow_type,
229
- description: primary.description,
230
- first_tool: primary.slug === 'researcher' ? 'tacit_research_prepare' : 'tacit_agent_delegate',
231
- script: buildScript(primary),
232
- ...(alternatives.length > 0 ? { alternatives } : {}),
233
- };
234
308
  return {
235
309
  content: [{ type: 'text', text: JSON.stringify(result, null, 2) }],
236
310
  };
package/dist/tools/iam.js CHANGED
@@ -1,11 +1,10 @@
1
1
  import { z } from 'zod';
2
2
  import { success, apiErrorResult } from './errors.js';
3
3
  export function registerIamTools(server, getClient) {
4
- server.tool('tacit_iam_grant_membership', 'Add a member to the workspace with an optional role, display name, and initial PIN', {
4
+ server.tool('tacit_iam_grant_membership', 'Add a member to the workspace with an optional role and display name', {
5
5
  email: z.string().describe('Email address of the new member'),
6
6
  role: z.string().optional().describe('Role to assign (e.g. "member", "admin")'),
7
7
  display_name: z.string().optional().describe('Display name for the member'),
8
- initial_pin: z.string().optional().describe('Initial login PIN'),
9
8
  }, async (args) => {
10
9
  try {
11
10
  const client = await getClient();
@@ -100,7 +99,7 @@ export function registerIamTools(server, getClient) {
100
99
  server.tool('tacit_iam_create_approval', 'Create an approval proof for a sensitive operation (offboard, transfer ownership)', {
101
100
  operation_type: z.string().describe('Type of operation requiring approval'),
102
101
  target_user_id: z.string().describe('ID of the user the operation targets'),
103
- pin: z.string().describe('Caller PIN for verification'),
102
+ pin: z.string().describe('Caller password for verification'),
104
103
  }, async (args) => {
105
104
  try {
106
105
  const client = await getClient();
@@ -15,6 +15,7 @@ export interface LogPayloadArgs {
15
15
  chapter_id?: string;
16
16
  participants?: string;
17
17
  supersedes_event_id?: string;
18
+ source?: string;
18
19
  }
19
20
  export declare function buildLogPayload(args: LogPayloadArgs): Record<string, unknown>;
20
21
  export interface RecallRequestArgs {
@@ -85,7 +85,7 @@ export function buildLogPayload(args) {
85
85
  event_type: backendType,
86
86
  title,
87
87
  raw_payload: args.description,
88
- metadata: { secretary_kind: eventType },
88
+ metadata: { secretary_kind: eventType, source: args.source ?? 'CHAT' },
89
89
  hint: `Logged as ${eventType} (backend: ${backendType}). Pass event_hint to override.`,
90
90
  };
91
91
  if (args.project_id)
@@ -161,6 +161,7 @@ export function registerSecretaryTools(server, getClient) {
161
161
  .optional()
162
162
  .describe('Comma-separated participant names or emails'),
163
163
  supersedes_event_id: z.string().uuid().optional().describe('UUID of a prior event this one supersedes'),
164
+ source: z.enum(['EMAIL', 'PHONE', 'SLACK', 'CHAT', 'OTHER']).optional().describe('Source channel for work event types (defaults to CHAT)'),
164
165
  }, async (args) => {
165
166
  try {
166
167
  const client = await getClient();
@@ -6,6 +6,11 @@
6
6
  *
7
7
  * Aliases: tacit_ask / tacit_compose route to this same handler.
8
8
  * stream:true selects the SSE variant and returns aggregated chunks.
9
+ *
10
+ * Voice (BUG-418): voice_mode voice_on/voice_only or voice_profile_id force the SSE
11
+ * path; voice is confirmed by voice_applied on the done event. voice_off picks the
12
+ * endpoint by `stream` alone: it sends voice_mode:'voice_off' on the SSE path only;
13
+ * the JSON path gets no voice fields.
9
14
  */
10
15
  import { z } from 'zod';
11
16
  import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
@@ -206,6 +211,37 @@ export declare const SYNTHESIZE_TOOL_DEF: {
206
211
  required: string[];
207
212
  };
208
213
  };
214
+ type ToolResult = {
215
+ content: Array<{
216
+ type: 'text';
217
+ text: string;
218
+ }>;
219
+ isError?: boolean;
220
+ };
221
+ /**
222
+ * BUG-418: parse an SSE data chunk and return it only if it is the `done` event.
223
+ * postSSE yields data payloads without the event name, so the done event is
224
+ * recognised by its voice fields or its synthesis_id.
225
+ */
226
+ export declare function parseSseDone(chunk: string): Record<string, unknown> | null;
227
+ /**
228
+ * BUG-418: shared voice check for SSE paths. Returns an error result when voice
229
+ * was requested but the server did not report voice_applied === true; null when
230
+ * voice was applied. Used by tacit_synthesize/ask/compose and tacit_compose_in_voice.
231
+ * `chunks` are the streamed chunks, used to show the user what the server said.
232
+ */
233
+ export declare function voiceNotAppliedResult(done: Record<string, unknown> | null, chunks?: string[]): ToolResult | null;
234
+ export interface VoiceProfileRow {
235
+ profile_id?: string;
236
+ voice_active?: boolean;
237
+ }
238
+ /** GET /voice/profiles; accepts only {profiles: [...]}. Throws on any other shape. */
239
+ export declare function listVoiceProfiles(client: TacitClient): Promise<VoiceProfileRow[]>;
240
+ /**
241
+ * BUG-418: the SSE path applies the single active profile. Returns an error unless
242
+ * EXACTLY one profile is active and it equals `explicitId` (when given).
243
+ */
244
+ export declare function requireSoleActiveProfile(client: TacitClient, explicitId?: string): Promise<ToolResult | null>;
209
245
  export interface ToolRequest {
210
246
  execute(): Promise<{
211
247
  content: Array<{
@@ -228,3 +264,4 @@ export declare function handleSynthesize(args: unknown): Promise<{
228
264
  isError?: boolean;
229
265
  }>;
230
266
  export declare function registerSynthesizeTools(server: McpServer, getClientFn: () => Promise<TacitClient>): void;
267
+ export {};
@@ -6,6 +6,11 @@
6
6
  *
7
7
  * Aliases: tacit_ask / tacit_compose route to this same handler.
8
8
  * stream:true selects the SSE variant and returns aggregated chunks.
9
+ *
10
+ * Voice (BUG-418): voice_mode voice_on/voice_only or voice_profile_id force the SSE
11
+ * path; voice is confirmed by voice_applied on the done event. voice_off picks the
12
+ * endpoint by `stream` alone: it sends voice_mode:'voice_off' on the SSE path only;
13
+ * the JSON path gets no voice fields.
9
14
  */
10
15
  import { z } from 'zod';
11
16
  import { getClient, TacitApiError, TokenExpiredError } from '../client.js';
@@ -39,7 +44,8 @@ export const SYNTHESIZE_TOOL_DEF = {
39
44
  name: 'tacit_synthesize',
40
45
  description: 'Synthesize knowledge from the Tacit workspace. ' +
41
46
  'stream:false (default) → POST /api/v1/mind/synthesize (JSON). ' +
42
- 'stream:true → POST /api/v1/mind/synthesize/stream (SSE; also exposed as tacit_ask / tacit_compose aliases).',
47
+ 'stream:true → POST /api/v1/mind/synthesize/stream (SSE; also exposed as tacit_ask / tacit_compose aliases). ' +
48
+ 'voice_mode voice_on/voice_only or voice_profile_id force the SSE path; voice is confirmed by voice_applied.',
43
49
  inputSchema: {
44
50
  type: 'object',
45
51
  properties: {
@@ -67,6 +73,93 @@ export const SYNTHESIZE_TOOL_DEF = {
67
73
  required: ['query'],
68
74
  },
69
75
  };
76
+ /**
77
+ * BUG-418: parse an SSE data chunk and return it only if it is the `done` event.
78
+ * postSSE yields data payloads without the event name, so the done event is
79
+ * recognised by its voice fields or its synthesis_id.
80
+ */
81
+ export function parseSseDone(chunk) {
82
+ try {
83
+ const parsed = JSON.parse(chunk);
84
+ if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)
85
+ && ('voice_applied' in parsed || 'voice_skip_reason' in parsed || 'synthesis_id' in parsed)) {
86
+ return parsed;
87
+ }
88
+ }
89
+ catch {
90
+ // not JSON — raw text chunk
91
+ }
92
+ return null;
93
+ }
94
+ const TAIL_MAX = 300;
95
+ /**
96
+ * BUG-418: shared voice check for SSE paths. Returns an error result when voice
97
+ * was requested but the server did not report voice_applied === true; null when
98
+ * voice was applied. Used by tacit_synthesize/ask/compose and tacit_compose_in_voice.
99
+ * `chunks` are the streamed chunks, used to show the user what the server said.
100
+ */
101
+ export function voiceNotAppliedResult(done, chunks = []) {
102
+ if (done && done['voice_applied'] === true)
103
+ return null;
104
+ const skip = done && typeof done['voice_skip_reason'] === 'string' ? done['voice_skip_reason'] : '';
105
+ let detail;
106
+ if (skip) {
107
+ detail = `voice_skip_reason: ${skip}`;
108
+ }
109
+ else if (done && !('voice_applied' in done) && done['scope_matched_zero_sources'] === true) {
110
+ detail = 'the request ended before generation (empty scope), so no voice fields were reported';
111
+ }
112
+ else if (done && !('voice_applied' in done)) {
113
+ detail = 'the done event had no voice fields; voice may be disabled on this cell (FEATURE_VOICE_SIGNATURE_V2)';
114
+ }
115
+ else {
116
+ detail = done ? 'voice_applied was false and the server gave no reason' : 'no done event received from the server';
117
+ }
118
+ let extra = '';
119
+ if (!skip) {
120
+ const last = chunks.filter((c) => parseSseDone(c) === null).pop();
121
+ if (last)
122
+ extra += ` Last streamed text: ${last.length > TAIL_MAX ? last.slice(0, TAIL_MAX) + '...' : last}`;
123
+ if (done && done['scope_matched_zero_sources'] !== undefined) {
124
+ extra += ` scope_matched_zero_sources: ${JSON.stringify(done['scope_matched_zero_sources'])}.`;
125
+ }
126
+ }
127
+ return {
128
+ content: [{
129
+ type: 'text',
130
+ text: `Voice was NOT applied (${detail}). The output is not in the user's voice; do not present it as voice-matched.${extra}`,
131
+ }],
132
+ isError: true,
133
+ };
134
+ }
135
+ /** GET /voice/profiles; accepts only {profiles: [...]}. Throws on any other shape. */
136
+ export async function listVoiceProfiles(client) {
137
+ const res = await client.get('/api/v1/voice/profiles');
138
+ const rows = res?.profiles;
139
+ if (!Array.isArray(rows))
140
+ throw new Error('unexpected /voice/profiles response shape (expected {profiles: [...]})');
141
+ return rows;
142
+ }
143
+ /**
144
+ * BUG-418: the SSE path applies the single active profile. Returns an error unless
145
+ * EXACTLY one profile is active and it equals `explicitId` (when given).
146
+ */
147
+ export async function requireSoleActiveProfile(client, explicitId) {
148
+ const active = (await listVoiceProfiles(client)).filter((p) => p.voice_active === true);
149
+ const hint = 'Use tacit_compose_in_voice with the grounded text in `content` (and voice_profile_id) to choose a profile.';
150
+ const fail = (text) => ({ content: [{ type: 'text', text }], isError: true });
151
+ if (active.length === 0) {
152
+ return fail(`No active voice profile exists (a profile needs 3+ samples and must be active). ${hint}`);
153
+ }
154
+ if (active.length > 1) {
155
+ const ids = active.map((p) => p.profile_id).join(', ');
156
+ return fail(`More than one voice profile is active (${ids}); the SSE path cannot choose between them. ${hint}`);
157
+ }
158
+ if (explicitId && active[0].profile_id !== explicitId) {
159
+ return fail(`voice_profile_id ${explicitId} is not the active profile (${active[0].profile_id}); the SSE path only uses the active profile. ${hint}`);
160
+ }
161
+ return null;
162
+ }
70
163
  /**
71
164
  * Build a synthesize request object. Call .execute() to perform the HTTP call.
72
165
  * Exported for testability (allows injecting a mock TacitClient).
@@ -108,16 +201,31 @@ export function buildSynthesizeRequest(client, input) {
108
201
  body['synthesis_mode'] = synthesis_mode;
109
202
  if (max_turns)
110
203
  body['max_turns'] = max_turns;
111
- if (voice_mode)
112
- body['voice_mode'] = voice_mode;
113
- if (voice_profile_id)
204
+ // BUG-418: voice fields are rejected by the JSON endpoint, so a voice request forces SSE.
205
+ // voice_off never forces SSE: on JSON it sends no voice fields; on SSE it sends
206
+ // voice_mode 'voice_off' (an absent mode would be treated as voice_on) and no profile id.
207
+ // Otherwise voice_profile_id implies voice_on.
208
+ const voiceOff = voice_mode === 'voice_off';
209
+ const voiceMode = voiceOff ? undefined : (voice_mode ?? (voice_profile_id ? 'voice_on' : undefined));
210
+ if (voiceMode)
211
+ body['voice_mode'] = voiceMode;
212
+ if (voiceMode && voice_profile_id)
114
213
  body['voice_profile_id'] = voice_profile_id;
214
+ if (voiceOff && stream)
215
+ body['voice_mode'] = 'voice_off';
115
216
  try {
116
- if (stream) {
117
- // SSE path: POST /api/v1/mind/synthesize/stream
217
+ if (stream || voiceMode) {
218
+ if (voiceMode) {
219
+ // The SSE path applies the single active profile; refuse ambiguity or a mismatch.
220
+ const blocked = await requireSoleActiveProfile(client, voice_profile_id);
221
+ if (blocked)
222
+ return blocked;
223
+ }
118
224
  const chunks = [];
119
225
  let structuredAnswer = null;
226
+ let done = null;
120
227
  for await (const chunk of client.postSSE('/api/v1/mind/synthesize/stream', body)) {
228
+ done = parseSseDone(chunk) ?? done;
121
229
  try {
122
230
  const parsed = JSON.parse(chunk);
123
231
  if (parsed.type === 'structured_answer') {
@@ -130,6 +238,17 @@ export function buildSynthesizeRequest(client, input) {
130
238
  }
131
239
  chunks.push(chunk);
132
240
  }
241
+ if (voiceMode === 'voice_on' || voiceMode === 'voice_only') {
242
+ const failed = voiceNotAppliedResult(done, chunks);
243
+ if (failed)
244
+ return failed;
245
+ }
246
+ if (voiceOff && done?.['voice_applied'] === true) {
247
+ return {
248
+ content: [{ type: 'text', text: "Voice was applied although voice_off was requested. The output is in the user's voice contrary to the request; do not present it as voice-free." }],
249
+ isError: true,
250
+ };
251
+ }
133
252
  if (chunks.length === 0 && !structuredAnswer) {
134
253
  return {
135
254
  content: [{ type: 'text', text: JSON.stringify({ chunks: 0, text: '' }) }],
@@ -208,7 +327,7 @@ export function registerSynthesizeTools(server, getClientFn) {
208
327
  const client = await getClientFn();
209
328
  return buildSynthesizeRequest(client, args).execute();
210
329
  };
211
- server.tool('tacit_synthesize', 'Synthesize knowledge from the Tacit workspace. synthesis_mode: burst (default, fast retrieval), orbit (agentic multi-turn), crew_compose (crew artifact generation). stream:false → JSON, stream:true → SSE.', SYNTH_SCHEMA, handler);
330
+ server.tool('tacit_synthesize', 'Synthesize knowledge from the Tacit workspace. synthesis_mode: burst (default, fast retrieval), orbit (agentic multi-turn), crew_compose (crew artifact generation). stream:false → JSON, stream:true → SSE. voice_mode voice_on/voice_only or voice_profile_id force the SSE path; voice is confirmed by voice_applied.', SYNTH_SCHEMA, handler);
212
331
  server.tool('tacit_ask', 'Ask a question against the Tacit workspace. Supports synthesis_mode: burst (default), orbit (agentic), crew_compose.', SYNTH_SCHEMA, handler);
213
332
  server.tool('tacit_compose', 'Compose knowledge from the Tacit workspace. Supports synthesis_mode: burst (default), orbit (agentic), crew_compose.', SYNTH_SCHEMA, handler);
214
333
  }
@@ -8,8 +8,9 @@
8
8
  * GET /profiles/:id/stats — get profile statistics
9
9
  * POST /profiles/:id/samples — upload a voice sample
10
10
  *
11
- * compose_in_voice uses POST /api/v1/mind/synthesize with
12
- * synthesis_mode=crew_compose + voice_mode=voice_on.
11
+ * compose_in_voice (BUG-418):
12
+ * with `content` -> POST /api/v1/voice/profiles/:id/generate (voice rewrite of grounded text)
13
+ * without content -> SSE /api/v1/mind/synthesize/stream, voice_mode=voice_on, voice_applied checked
13
14
  */
14
15
  import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
15
16
  import { TacitClient } from '../client.js';