@ema.co/mcp-toolkit 0.2.3 → 0.3.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.
@@ -4,6 +4,8 @@
4
4
  * Each handler dispatches based on mode/flags following Unix CLI patterns.
5
5
  */
6
6
  import { fingerprintPersona } from "../sync.js";
7
+ import { createVersionStorage } from "../sdk/version-storage.js";
8
+ import { createVersionPolicyEngine } from "../sdk/version-policy.js";
7
9
  import { AGENT_CATALOG, WORKFLOW_PATTERNS, QUALIFYING_QUESTIONS, PLATFORM_CONCEPTS, WORKFLOW_EXECUTION_MODEL, COMMON_MISTAKES, DEBUG_CHECKLIST, GUIDANCE_TOPICS, VOICE_PERSONA_TEMPLATE, getAgentByName, getWidgetsForPersonaType, checkTypeCompatibility, getQualifyingQuestionsByCategory, getRequiredQualifyingQuestions, getConceptByTerm, suggestAgentsForUseCase, validateWorkflowPrompt, detectWorkflowIssues, validateWorkflowConnections, suggestWorkflowFixes, } from "../sdk/knowledge.js";
8
10
  import { compileWorkflow } from "../sdk/workflow-generator.js";
9
11
  import { parseInput, intentToSpec } from "../sdk/workflow-intent.js";
@@ -23,7 +25,7 @@ export async function handleEnv(_args, getEnvironments) {
23
25
  // ═══════════════════════════════════════════════════════════════════════════
24
26
  // PERSONA Handler
25
27
  // ═══════════════════════════════════════════════════════════════════════════
26
- export async function handlePersona(args, client, getTemplateId, createClientForEnv) {
28
+ export async function handlePersona(args, client, getTemplateId, createClientForEnv, versionContext) {
27
29
  const id = args.id;
28
30
  const identifier = args.identifier; // deprecated alias
29
31
  const idOrName = id ?? identifier;
@@ -171,6 +173,251 @@ export async function handlePersona(args, client, getTemplateId, createClientFor
171
173
  count: templates.size,
172
174
  };
173
175
  }
176
+ // ─────────────── Version Management Modes ───────────────
177
+ case "version_create": {
178
+ if (!idOrName) {
179
+ return { error: "id required for version_create mode" };
180
+ }
181
+ if (!versionContext) {
182
+ return { error: "Version tracking not configured. Provide workspaceRoot in context." };
183
+ }
184
+ const persona = await resolvePersona(client, idOrName);
185
+ if (!persona) {
186
+ return { error: `Persona not found: ${idOrName}` };
187
+ }
188
+ // Fetch full persona with workflow
189
+ const fullPersona = await client.getPersonaById(persona.id);
190
+ if (!fullPersona) {
191
+ return { error: `Could not fetch full persona: ${persona.id}` };
192
+ }
193
+ const storage = createVersionStorage(versionContext.workspaceRoot);
194
+ const engine = createVersionPolicyEngine(storage);
195
+ const result = engine.forceCreateVersion(fullPersona, {
196
+ environment: versionContext.environment,
197
+ tenant_id: versionContext.tenant_id,
198
+ message: args.message,
199
+ created_by: "mcp-toolkit",
200
+ });
201
+ if (!result.created || !result.version) {
202
+ return { error: result.reason };
203
+ }
204
+ return {
205
+ success: true,
206
+ version: {
207
+ id: result.version.id,
208
+ version_number: result.version.version_number,
209
+ version_name: result.version.version_name,
210
+ content_hash: result.version.content_hash,
211
+ created_at: result.version.created_at,
212
+ message: result.version.message,
213
+ },
214
+ changes_from_parent: result.changes_from_parent,
215
+ versions_pruned: result.versions_pruned,
216
+ };
217
+ }
218
+ case "version_list": {
219
+ if (!idOrName) {
220
+ return { error: "id required for version_list mode" };
221
+ }
222
+ if (!versionContext) {
223
+ return { error: "Version tracking not configured. Provide workspaceRoot in context." };
224
+ }
225
+ const persona = await resolvePersona(client, idOrName);
226
+ if (!persona) {
227
+ return { error: `Persona not found: ${idOrName}` };
228
+ }
229
+ const storage = createVersionStorage(versionContext.workspaceRoot);
230
+ const engine = createVersionPolicyEngine(storage);
231
+ const versions = engine.listVersions(persona.id, {
232
+ limit: args.limit,
233
+ });
234
+ return {
235
+ persona_id: persona.id,
236
+ persona_name: persona.name,
237
+ versions,
238
+ count: versions.length,
239
+ };
240
+ }
241
+ case "version_get": {
242
+ if (!idOrName) {
243
+ return { error: "id required for version_get mode" };
244
+ }
245
+ if (!versionContext) {
246
+ return { error: "Version tracking not configured. Provide workspaceRoot in context." };
247
+ }
248
+ const persona = await resolvePersona(client, idOrName);
249
+ if (!persona) {
250
+ return { error: `Persona not found: ${idOrName}` };
251
+ }
252
+ const versionId = args.version ?? "latest";
253
+ const storage = createVersionStorage(versionContext.workspaceRoot);
254
+ const engine = createVersionPolicyEngine(storage);
255
+ const version = engine.getVersion(persona.id, versionId);
256
+ if (!version) {
257
+ return { error: `Version not found: ${versionId}` };
258
+ }
259
+ return {
260
+ persona_id: persona.id,
261
+ persona_name: persona.name,
262
+ version: {
263
+ id: version.id,
264
+ version_number: version.version_number,
265
+ version_name: version.version_name,
266
+ content_hash: version.content_hash,
267
+ created_at: version.created_at,
268
+ created_by: version.created_by,
269
+ trigger: version.trigger,
270
+ message: version.message,
271
+ changes_summary: version.changes_summary,
272
+ },
273
+ snapshot: {
274
+ display_name: version.snapshot.display_name,
275
+ description: version.snapshot.description,
276
+ workflow_id: version.snapshot.workflow_id,
277
+ trigger_type: version.snapshot.trigger_type,
278
+ embedding_enabled: version.snapshot.embedding_enabled,
279
+ has_workflow: !!version.snapshot.workflow_definition,
280
+ has_proto_config: !!version.snapshot.proto_config,
281
+ },
282
+ };
283
+ }
284
+ case "version_compare": {
285
+ if (!idOrName) {
286
+ return { error: "id required for version_compare mode" };
287
+ }
288
+ if (!versionContext) {
289
+ return { error: "Version tracking not configured. Provide workspaceRoot in context." };
290
+ }
291
+ const v1 = args.v1;
292
+ const v2 = args.v2;
293
+ if (!v1 || !v2) {
294
+ return { error: "v1 and v2 required for version_compare mode" };
295
+ }
296
+ const persona = await resolvePersona(client, idOrName);
297
+ if (!persona) {
298
+ return { error: `Persona not found: ${idOrName}` };
299
+ }
300
+ const storage = createVersionStorage(versionContext.workspaceRoot);
301
+ const engine = createVersionPolicyEngine(storage);
302
+ const result = engine.compareVersions(persona.id, v1, v2);
303
+ if (!result.success) {
304
+ return { error: result.error };
305
+ }
306
+ return {
307
+ persona_id: persona.id,
308
+ persona_name: persona.name,
309
+ comparison: {
310
+ v1: result.diff?.v1,
311
+ v2: result.diff?.v2,
312
+ identical: result.diff?.identical,
313
+ changed_fields: result.diff?.changed_fields,
314
+ workflow_diff: result.diff?.workflow_diff,
315
+ },
316
+ summary: result.summary,
317
+ };
318
+ }
319
+ case "version_restore": {
320
+ if (!idOrName) {
321
+ return { error: "id required for version_restore mode" };
322
+ }
323
+ if (!versionContext) {
324
+ return { error: "Version tracking not configured. Provide workspaceRoot in context." };
325
+ }
326
+ const versionId = args.version;
327
+ if (!versionId) {
328
+ return { error: "version required for version_restore mode" };
329
+ }
330
+ const persona = await resolvePersona(client, idOrName);
331
+ if (!persona) {
332
+ return { error: `Persona not found: ${idOrName}` };
333
+ }
334
+ const storage = createVersionStorage(versionContext.workspaceRoot);
335
+ const engine = createVersionPolicyEngine(storage);
336
+ const restoreData = engine.getRestoreData(persona.id, versionId);
337
+ if (!restoreData.success || !restoreData.restore_payload) {
338
+ return { error: restoreData.error ?? "Failed to get restore data" };
339
+ }
340
+ // Create a version snapshot before restoring (audit trail)
341
+ const fullPersona = await client.getPersonaById(persona.id);
342
+ if (fullPersona) {
343
+ engine.forceCreateVersion(fullPersona, {
344
+ environment: versionContext.environment,
345
+ tenant_id: versionContext.tenant_id,
346
+ message: `Before restore to ${restoreData.version?.version_name}`,
347
+ created_by: "mcp-toolkit",
348
+ });
349
+ }
350
+ // Apply the restore
351
+ const payload = restoreData.restore_payload;
352
+ await client.updateAiEmployee({
353
+ persona_id: payload.persona_id,
354
+ name: payload.name,
355
+ description: payload.description,
356
+ proto_config: payload.proto_config,
357
+ workflow: payload.workflow ?? undefined,
358
+ welcome_messages: payload.welcome_messages ?? undefined,
359
+ embedding_enabled: payload.embedding_enabled ?? undefined,
360
+ });
361
+ // Create post-restore version
362
+ const restoredPersona = await client.getPersonaById(persona.id);
363
+ if (restoredPersona) {
364
+ engine.forceCreateVersion(restoredPersona, {
365
+ environment: versionContext.environment,
366
+ tenant_id: versionContext.tenant_id,
367
+ message: `Restored to ${restoreData.version?.version_name}`,
368
+ created_by: "mcp-toolkit",
369
+ });
370
+ }
371
+ return {
372
+ success: true,
373
+ persona_id: persona.id,
374
+ restored_to: {
375
+ version_id: restoreData.version?.id,
376
+ version_name: restoreData.version?.version_name,
377
+ version_number: restoreData.version?.version_number,
378
+ },
379
+ message: `Persona restored to ${restoreData.version?.version_name}`,
380
+ };
381
+ }
382
+ case "version_policy": {
383
+ if (!idOrName) {
384
+ return { error: "id required for version_policy mode" };
385
+ }
386
+ if (!versionContext) {
387
+ return { error: "Version tracking not configured. Provide workspaceRoot in context." };
388
+ }
389
+ const persona = await resolvePersona(client, idOrName);
390
+ if (!persona) {
391
+ return { error: `Persona not found: ${idOrName}` };
392
+ }
393
+ const storage = createVersionStorage(versionContext.workspaceRoot);
394
+ const engine = createVersionPolicyEngine(storage);
395
+ // Check if we're updating or just getting
396
+ const hasUpdates = args.auto_on_deploy !== undefined ||
397
+ args.auto_on_sync !== undefined ||
398
+ args.max_versions !== undefined;
399
+ if (hasUpdates) {
400
+ const updated = engine.updatePolicy(persona.id, {
401
+ auto_version_on_deploy: args.auto_on_deploy,
402
+ auto_version_on_sync: args.auto_on_sync,
403
+ max_versions: args.max_versions,
404
+ });
405
+ return {
406
+ success: true,
407
+ persona_id: persona.id,
408
+ persona_name: persona.name,
409
+ policy: updated,
410
+ message: "Policy updated",
411
+ };
412
+ }
413
+ // Just get current policy
414
+ const policy = engine.getPolicy(persona.id);
415
+ return {
416
+ persona_id: persona.id,
417
+ persona_name: persona.name,
418
+ policy,
419
+ };
420
+ }
174
421
  default:
175
422
  return { error: `Unknown mode: ${effectiveMode}` };
176
423
  }
@@ -25,6 +25,8 @@ import { loadConfigOptional } from "../sdk/config.js";
25
25
  import { resolveSyncBehavior, loadSyncOptions } from "../sdk/sync-options.js";
26
26
  import { SyncSDK } from "../sdk/sync.js";
27
27
  import { fingerprintPersona, transformWorkflowForTarget, getCleanDescription, buildDescriptionWithSyncTag } from "../sync.js";
28
+ import { createVersionStorage } from "../sdk/version-storage.js";
29
+ import { createVersionPolicyEngine } from "../sdk/version-policy.js";
28
30
  import { SYNC_METADATA_KEY } from "../sdk/models.js";
29
31
  // Auto Builder Knowledge
30
32
  import { AGENT_CATALOG, WORKFLOW_PATTERNS, QUALIFYING_QUESTIONS, PLATFORM_CONCEPTS, WORKFLOW_EXECUTION_MODEL, COMMON_MISTAKES, DEBUG_CHECKLIST, GUIDANCE_TOPICS, VOICE_PERSONA_TEMPLATE, PROJECT_TYPES, getAgentsByCategory, getAgentByName, getWidgetsForPersonaType, checkTypeCompatibility, getQualifyingQuestionsByCategory, getConceptByTerm, suggestAgentsForUseCase, validateWorkflowPrompt,
@@ -4205,13 +4207,20 @@ const toolHandlers = {
4205
4207
  })));
4206
4208
  },
4207
4209
  persona: async (args) => {
4208
- const client = createClient(args.env);
4210
+ const targetEnv = args.env ?? getDefaultEnvName();
4211
+ const client = createClient(targetEnv);
4209
4212
  const DEFAULT_TEMPLATES = {
4210
4213
  voice: "00000000-0000-0000-0000-00000000001e",
4211
4214
  chat: "00000000-0000-0000-0000-000000000004",
4212
4215
  dashboard: "00000000-0000-0000-0000-000000000002",
4213
4216
  };
4214
- return handlePersona(args, client, (type) => DEFAULT_TEMPLATES[type], (env) => createClient(env));
4217
+ // Build version context for version management modes
4218
+ const versionContext = {
4219
+ workspaceRoot: process.cwd(),
4220
+ environment: targetEnv,
4221
+ tenant_id: targetEnv, // Use env name as tenant identifier
4222
+ };
4223
+ return handlePersona(args, client, (type) => DEFAULT_TEMPLATES[type], (env) => createClient(env), versionContext);
4215
4224
  },
4216
4225
  // Note: 'workflow' handler already exists above - consolidated version adds analyze modes
4217
4226
  // The existing 'workflow' handler is kept for backward compatibility
@@ -4358,7 +4367,34 @@ toolHandlers.workflow = async (args) => {
4358
4367
  }
4359
4368
  const validateFirst = normalizedArgs.validate !== false; // default true
4360
4369
  const autoFix = normalizedArgs.auto_fix === true; // default false
4361
- return legacyDeployWorkflow({
4370
+ const targetEnv = normalizedArgs.env ?? getDefaultEnvName();
4371
+ // ─────────────── Version tracking (pre-deploy snapshot) ───────────────
4372
+ let versionCreated;
4373
+ try {
4374
+ const client = createClient(targetEnv);
4375
+ const personaBefore = await client.getPersonaById(personaId);
4376
+ if (personaBefore) {
4377
+ const storage = createVersionStorage(process.cwd());
4378
+ const engine = createVersionPolicyEngine(storage);
4379
+ // Check policy and create version if allowed
4380
+ const result = engine.createVersionIfAllowed(personaBefore, "deploy", {
4381
+ environment: targetEnv,
4382
+ tenant_id: targetEnv,
4383
+ message: "Pre-deploy snapshot",
4384
+ created_by: "mcp-toolkit",
4385
+ });
4386
+ if (result.created && result.version) {
4387
+ versionCreated = {
4388
+ id: result.version.id,
4389
+ version_name: result.version.version_name,
4390
+ };
4391
+ }
4392
+ }
4393
+ }
4394
+ catch {
4395
+ // Version tracking is best-effort - don't fail deploy if it errors
4396
+ }
4397
+ const deployResult = await legacyDeployWorkflow({
4362
4398
  persona_id: personaId,
4363
4399
  workflow_def: workflowDef,
4364
4400
  proto_config: normalizedArgs.proto_config,
@@ -4366,6 +4402,11 @@ toolHandlers.workflow = async (args) => {
4366
4402
  auto_fix: autoFix,
4367
4403
  env: normalizedArgs.env,
4368
4404
  });
4405
+ // Add version info to result if created
4406
+ if (versionCreated && deployResult && typeof deployResult === "object") {
4407
+ deployResult.version_snapshot = versionCreated;
4408
+ }
4409
+ return deployResult;
4369
4410
  }
4370
4411
  case "optimize": {
4371
4412
  // optimize_workflow supports both:
@@ -46,7 +46,7 @@ export function generateConsolidatedTools(envNames, defaultEnv) {
46
46
  inputSchema: { type: "object", properties: {}, required: [] },
47
47
  },
48
48
  // ═══════════════════════════════════════════════════════════════════════
49
- // 2. PERSONA - AI Employee management (CRUD + compare)
49
+ // 2. PERSONA - AI Employee management (CRUD + compare + versioning)
50
50
  // ═══════════════════════════════════════════════════════════════════════
51
51
  {
52
52
  name: "persona",
@@ -71,7 +71,15 @@ export function generateConsolidatedTools(envNames, defaultEnv) {
71
71
  persona(id="abc-123", mode="compare", compare_to="def-456")
72
72
 
73
73
  **Templates** (list available templates):
74
- persona(templates=true)`,
74
+ persona(templates=true)
75
+
76
+ **Version Management** (track configuration history):
77
+ persona(id="abc-123", mode="version_create", message="Before major update")
78
+ persona(id="abc-123", mode="version_list")
79
+ persona(id="abc-123", mode="version_get", version="v3")
80
+ persona(id="abc-123", mode="version_compare", v1="v2", v2="v3")
81
+ persona(id="abc-123", mode="version_restore", version="v2")
82
+ persona(id="abc-123", mode="version_policy", auto_on_deploy=true)`,
75
83
  inputSchema: withEnv({
76
84
  // ID (or exact name) (optional - if omitted with all=true, lists all)
77
85
  id: {
@@ -87,7 +95,7 @@ export function generateConsolidatedTools(envNames, defaultEnv) {
87
95
  // Mode (defaults to "get" if id provided, "list" if all=true)
88
96
  mode: {
89
97
  type: "string",
90
- enum: ["get", "list", "create", "update", "compare"],
98
+ enum: ["get", "list", "create", "update", "compare", "version_create", "version_list", "version_get", "version_compare", "version_restore", "version_policy"],
91
99
  description: "Operation mode. Default: 'get' with id, 'list' without."
92
100
  },
93
101
  // List/Search flags
@@ -116,6 +124,14 @@ export function generateConsolidatedTools(envNames, defaultEnv) {
116
124
  compare_env: { type: "string", description: "Environment of compare_to persona" },
117
125
  // Templates flag
118
126
  templates: { type: "boolean", description: "List available templates" },
127
+ // Version management flags
128
+ version: { type: "string", description: "Version identifier (e.g., 'v3', 'latest', or UUID)" },
129
+ v1: { type: "string", description: "First version for comparison (version_compare mode)" },
130
+ v2: { type: "string", description: "Second version for comparison (version_compare mode)" },
131
+ message: { type: "string", description: "Version message/description (version_create mode)" },
132
+ auto_on_deploy: { type: "boolean", description: "Auto-create version on deploy (version_policy mode)" },
133
+ auto_on_sync: { type: "boolean", description: "Auto-create version on sync (version_policy mode)" },
134
+ max_versions: { type: "number", description: "Max versions to keep (version_policy mode)" },
119
135
  }),
120
136
  },
121
137
  // ═══════════════════════════════════════════════════════════════════════
package/dist/sdk/index.js CHANGED
@@ -37,3 +37,11 @@ buildVoiceConfig, buildChatConfig, } from "./workflow-generator.js";
37
37
  export { parseInput, validateIntent, intentToSpec, detectInputType, parseNaturalLanguage, parsePartialSpec, } from "./workflow-intent.js";
38
38
  // Generation Schema (Compact format for LLM-based generation)
39
39
  export { generateSchema, generateSchemaMarkdown, buildCompactAgents, buildTypeRules, buildConstraints, getAgentSchema, isTypeCompatible, getRecommendedInput, } from "./generation-schema.js";
40
+ // Version Tracking (Persona version history management)
41
+ export {
42
+ // Core functions
43
+ hashSnapshot, generateVersionId, generateVersionName, nowIso, createSnapshotFromPersona, createVersionSnapshot, compareVersions, generateChangesSummary, fingerprintPersona, extractDataSources, } from "./version-tracking.js";
44
+ // Version Storage (Git-backed local storage)
45
+ export { VersionStorage, createVersionStorage, } from "./version-storage.js";
46
+ // Version Policy Engine (Automatic versioning decisions)
47
+ export { VersionPolicyEngine, createVersionPolicyEngine, } from "./version-policy.js";