@mtkn/mega-agent 0.4.0 → 0.5.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/README.md CHANGED
@@ -14,7 +14,7 @@ AI-powered agent infrastructure for Express + Prisma backends. Drop-in chat API
14
14
  - **Incident detection** — anomaly detection with severity levels
15
15
  - **Workflow automation** — schedule, event, threshold, and manual triggers
16
16
  - **Artifact storage** — reports, tables, charts, code, images, datasets
17
- - **MCP support** — Model Context Protocol for external data sources
17
+ - **MCP support** — Model Context Protocol for external data sources _(not managed by `createMegaAgent`; must be initialized and disposed separately — see [MCP section](#mcp))_
18
18
  - **Prisma persistence** — 12 models, fully typed
19
19
 
20
20
  ## Quick Start
@@ -55,7 +55,6 @@ app.use('/api/chat', agent.createChatRouter(authMiddleware));
55
55
  |---|---|
56
56
  | Qdrant | Vector database for semantic search |
57
57
  | OpenAI API | Embedding model (`text-embedding-3-small`) |
58
- | Redis + BullMQ | Job queue (for workflows) |
59
58
 
60
59
  ## Installation
61
60
 
@@ -69,7 +68,7 @@ npm install -D prisma @types/express typescript
69
68
 
70
69
  ## Prisma Schema Setup
71
70
 
72
- The package requires 16 enums and 12 models in your Prisma schema.
71
+ The package requires 15 enums and 12 models in your Prisma schema.
73
72
 
74
73
  ### Option A: Automatic Sync (Recommended)
75
74
 
@@ -181,8 +180,8 @@ npx prisma generate
181
180
 
182
181
  ```typescript
183
182
  interface MegaAgentConfig {
184
- /** Prisma client instance */
185
- prisma: PrismaClient;
183
+ /** Prisma client instance (also accepts TransactionClient) */
184
+ prisma: PrismaClient | Prisma.TransactionClient;
186
185
 
187
186
  /** Logger with info/error/warn/debug methods */
188
187
  logger: LoggerLike;
@@ -208,6 +207,7 @@ interface MegaAgentConfig {
208
207
  host: string; // default: 'localhost'
209
208
  port: number; // default: 6333
210
209
  apiKey?: string;
210
+ userIdType?: 'string' | 'number'; // default: 'number'
211
211
  };
212
212
  };
213
213
 
@@ -411,6 +411,43 @@ if (getWorkflowServiceDeps()) {
411
411
  }
412
412
  ```
413
413
 
414
+ You can also mount the chat router directly using `createChatRoutes` — the same low-level function that `agent.createChatRouter()` uses internally:
415
+
416
+ ```typescript
417
+ import { createChatRoutes, ChatController } from '@mtkn/mega-agent';
418
+
419
+ // Requires services to be initialized (via createMegaAgent or manually)
420
+ const controller = new ChatController();
421
+ const router = createChatRoutes(controller, authMiddleware);
422
+ app.use('/api/chat', router);
423
+ ```
424
+
425
+ ### MCP
426
+
427
+ MCP services (`McpService`, `SourceService`) are **not** managed by `createMegaAgent()`. They must be initialized and disposed separately:
428
+
429
+ ```typescript
430
+ import {
431
+ initMcpService,
432
+ McpService,
433
+ disposeMcpService,
434
+ initSourceService,
435
+ SourceService,
436
+ disposeSourceService,
437
+ } from '@mtkn/mega-agent';
438
+
439
+ // Initialize
440
+ initMcpService({ prisma, logger });
441
+ initSourceService({ prisma, logger });
442
+
443
+ const mcp = new McpService();
444
+ const sources = new SourceService();
445
+
446
+ // Dispose (async — must be awaited)
447
+ await disposeMcpService();
448
+ await disposeSourceService();
449
+ ```
450
+
414
451
  ## API Endpoints
415
452
 
416
453
  The chat router creates the following endpoints:
@@ -447,9 +484,15 @@ Content-Type: application/json
447
484
  "data": {
448
485
  "userMessage": { "id": "...", "role": "USER", "content": "..." },
449
486
  "assistantMessage": { "id": "...", "role": "ASSISTANT", "content": "..." },
450
- "memories": [],
487
+ "usedMemories": [],
451
488
  "tokens": { "prompt": 1200, "completion": 350, "total": 1550 },
452
- "latencyMs": 2340
489
+ "latencyMs": 2340,
490
+ "structured": {
491
+ "type": "answer",
492
+ "content": "Here are today's production stats...",
493
+ "quality": { "signal": "strong", "confidence": 0.92 },
494
+ "toolsUsed": [{ "name": "get_dashboard", "description": "Get dashboard data", "executionTimeMs": 120 }]
495
+ }
453
496
  }
454
497
  }
455
498
  ```
@@ -462,6 +505,7 @@ Content-Type: application/json
462
505
  "data": {
463
506
  "userMessage": { "id": "...", "role": "USER", "content": "..." },
464
507
  "assistantMessage": { "id": "...", "role": "ASSISTANT", "content": "I want to execute **create_order**..." },
508
+ "usedMemories": [],
465
509
  "pendingApproval": {
466
510
  "id": "a1b2c3d4-...",
467
511
  "chatId": "chat-id",
@@ -477,6 +521,32 @@ Content-Type: application/json
477
521
 
478
522
  Use the `pendingApproval.id` value as the `approvalId` when calling the approve or reject endpoints.
479
523
 
524
+ ### Structured Response
525
+
526
+ The `structured` field is a parsed representation of the LLM output, designed for rich frontend rendering. It is present on both regular and approve responses.
527
+
528
+ ```typescript
529
+ interface StructuredResponse {
530
+ type: 'answer' | 'table' | 'chart' | 'agent_created' | 'report' | 'error';
531
+ content: string; // Markdown content (always present)
532
+ data?: TableData | ChartData | AgentData | Record<string, unknown>;
533
+ quality?: { signal: 'strong' | 'moderate' | 'weak'; confidence: number; reasoning?: string };
534
+ sources?: { name: string; type: 'memory' | 'database' | 'api' | 'tool' | 'document'; relevance: number }[];
535
+ toolsUsed?: { name: string; description: string; executionTimeMs?: number }[];
536
+ memory?: { saved?: boolean; savedContent?: string; referencedIds?: string[] };
537
+ artifact?: { suggestedTitle: string; type: 'TABLE' | 'CHART' | 'REPORT' | 'CODE' | 'DATASET'; data: unknown };
538
+ }
539
+ ```
540
+
541
+ | Type | When |
542
+ |------|------|
543
+ | `answer` | Default — plain text or markdown response |
544
+ | `table` | Response contains tabular data (`data` is `TableData`) |
545
+ | `chart` | Response contains chart data (`data` is `ChartData`) |
546
+ | `report` | Response is a generated report |
547
+ | `agent_created` | A workflow agent was created (`data` is `AgentData`) |
548
+ | `error` | An error occurred during processing |
549
+
480
550
  **SSE Streaming:**
481
551
 
482
552
  When `stream: true`, the response uses Server-Sent Events:
@@ -484,10 +554,10 @@ When `stream: true`, the response uses Server-Sent Events:
484
554
  ```
485
555
  Content-Type: text/event-stream
486
556
 
487
- data: {"type":"chunk","content":"Here are"}
488
- data: {"type":"chunk","content":" today's stats..."}
489
- data: {"type":"tool_call","name":"get_dashboard","args":{}}
490
- data: {"type":"done","tokens":{"prompt":1200,"completion":350}}
557
+ data: {"type":"content","content":"Here are"}
558
+ data: {"type":"content","content":" today's stats..."}
559
+ data: {"type":"tool_status","toolName":"get_dashboard","content":"Executing get_dashboard..."}
560
+ data: {"type":"done"}
491
561
  ```
492
562
 
493
563
  ### Approve Tool Call
@@ -511,7 +581,13 @@ The server executes the tool using the original `toolName` and `arguments` store
511
581
  "data": {
512
582
  "assistantMessage": { "id": "...", "role": "ASSISTANT", "content": "Order created successfully..." },
513
583
  "tokens": { "prompt": 2100, "completion": 220, "total": 2320 },
514
- "latencyMs": 3100
584
+ "latencyMs": 3100,
585
+ "structured": {
586
+ "type": "answer",
587
+ "content": "Order created successfully...",
588
+ "quality": { "signal": "strong", "confidence": 0.95 },
589
+ "toolsUsed": [{ "name": "create_order", "description": "Create a new order. Requires approval.", "executionTimeMs": 85 }]
590
+ }
515
591
  }
516
592
  }
517
593
  ```
@@ -575,14 +651,14 @@ Agent processes with LLM
575
651
 
576
652
  ├── POST /:id/approve { approvalId } → executes tool → agent continues
577
653
 
578
- └── POST /:id/reject { approvalId } → approval cancelled → agent informed
654
+ └── POST /:id/reject { approvalId } → approval cancelled
579
655
  ```
580
656
 
581
657
  Conversation state (LLM message history) is stored **server-side** in an in-memory store with a 10-minute TTL. The client only receives an opaque `approvalId` — never the raw conversation state.
582
658
 
583
659
  ## Prisma Models
584
660
 
585
- The package uses 12 models and 16 enums:
661
+ The package uses 12 models and 15 enums:
586
662
 
587
663
  | Model | Purpose |
588
664
  |-------|---------|
@@ -599,6 +675,20 @@ The package uses 12 models and 16 enums:
599
675
  | `AiTimelineEvent` | Event log for audit trail |
600
676
  | `AiUserPreferences` | Per-user AI settings |
601
677
 
678
+ ### MemoryType Enum
679
+
680
+ The `create_memory` tool and `MemoryService` use the `MemoryType` enum to categorize stored memories:
681
+
682
+ | Value | Description |
683
+ |-------|-------------|
684
+ | `FACT` | Concrete, verifiable piece of information |
685
+ | `INSIGHT` | Analytical observation or inference derived from data |
686
+ | `DECISION` | A choice or resolution made by the user or system |
687
+ | `PATTERN` | Recurring trend or behavior detected over time |
688
+ | `INCIDENT` | Anomaly or notable event captured by the incident service |
689
+ | `REPORT_SUMMARY` | Condensed summary of a generated report |
690
+ | `USER_PREFERENCE` | User-specific setting or preference |
691
+
602
692
  ## Environment Variables
603
693
 
604
694
  | Variable | Required | Description | Default |
@@ -697,6 +787,20 @@ All service methods accept `UserId` for the `userId` parameter, so your app work
697
787
 
698
788
  ## Changelog
699
789
 
790
+ ### v0.5.0
791
+
792
+ - **Breaking: `bullmq` dependency removed** — Redis + BullMQ is no longer a dependency. Workflow job queue must be provided externally if needed.
793
+ - **Breaking: `MemoryType` enum changed** — `PROCEDURE` removed; `INCIDENT`, `REPORT_SUMMARY`, `USER_PREFERENCE` added.
794
+ - **Breaking: SSE event types renamed** — `chunk` → `content`, `tool_call` → `tool_status`. `done` event no longer includes token data.
795
+ - **Breaking: Response field renamed** — `memories` → `usedMemories` in chat and approve responses.
796
+ - **Structured response** — New `structured` field in chat and approve responses with typed output (`answer`, `table`, `chart`, `report`, `agent_created`, `error`), quality signal, sources, and tools used.
797
+ - **TransactionClient support** — `MegaAgentConfig.prisma` now accepts `PrismaClient | Prisma.TransactionClient`.
798
+ - **`createChatRoutes` export** — Low-level chat router factory is now documented and available for manual mounting.
799
+ - **MCP lifecycle docs** — `McpService` and `SourceService` are not managed by `createMegaAgent`; init/dispose documented separately.
800
+ - **`userIdType` config option** — Qdrant config now accepts `userIdType: 'string' | 'number'`.
801
+ - **Package rename refs** — Internal comments updated from `@7style/mega-agent` to `@mtkn/mega-agent`.
802
+ - **Enum count fix** — Documentation corrected from 16 enums to 15.
803
+
700
804
  ### v0.4.0
701
805
 
702
806
  - **Breaking: Zero LLM providers now throws** — `createMegaAgent()` throws `ConfigValidationError` if `llm.providers` is empty. Previously it only logged a warning, causing all chat operations to fail at runtime.
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @7style/mega-agent
2
+ * @mtkn/mega-agent
3
3
  *
4
4
  * AI-powered agent services for memory, chat, LLM, embeddings,
5
5
  * vector search, MCP, incidents, workflows, and artifacts.
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @7style/mega-agent
2
+ * @mtkn/mega-agent
3
3
  *
4
4
  * AI-powered agent services for memory, chat, LLM, embeddings,
5
5
  * vector search, MCP, incidents, workflows, and artifacts.
@@ -29,7 +29,7 @@ export const CORE_TOOLS = [
29
29
  properties: {
30
30
  title: { type: 'string', description: 'Memory title' },
31
31
  content: { type: 'string', description: 'Content' },
32
- type: { type: 'string', description: 'Type', enum: ['FACT', 'INSIGHT', 'DECISION', 'PATTERN', 'PROCEDURE'] },
32
+ type: { type: 'string', description: 'Type', enum: ['FACT', 'INSIGHT', 'DECISION', 'PATTERN', 'INCIDENT', 'REPORT_SUMMARY', 'USER_PREFERENCE'] },
33
33
  },
34
34
  required: ['title', 'content'],
35
35
  },
@@ -1 +1 @@
1
- {"version":3,"file":"core-tools.js","sourceRoot":"","sources":["../../src/tools/core-tools.ts"],"names":[],"mappings":"AAMA,MAAM,CAAC,MAAM,UAAU,GAAqB;IAC1C;QACE,IAAI,EAAE,eAAe;QACrB,WAAW,EAAE,4CAA4C;QACzD,QAAQ,EAAE,MAAM;QAChB,WAAW,EAAE;YACX,IAAI,EAAE,QAAQ;YACd,UAAU,EAAE;gBACV,KAAK,EAAE,EAAE,IAAI,EAAE,QAAQ,EAAE,WAAW,EAAE,cAAc,EAAE;gBACtD,KAAK,EAAE,EAAE,IAAI,EAAE,QAAQ,EAAE,WAAW,EAAE,KAAK,EAAE;aAC9C;YACD,QAAQ,EAAE,CAAC,OAAO,CAAC;SACpB;QACD,OAAO,EAAE,KAAK,EAAE,IAAI,EAAE,MAAM,EAAE,EAAE;YAC9B,MAAM,EAAE,oBAAoB,EAAE,aAAa,EAAE,GAAG,MAAM,MAAM,CAAC,oBAAoB,CAAC,CAAC;YACnF,IAAI,CAAC,oBAAoB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CAAC,OAAiB;gBAC/B,IAAI,EAAG,IAAI,CAAC,IAAe,IAAI,SAAS;gBACxC,UAAU,EAAE,MAAM;gBAClB,UAAU,EAAE,GAAG;aAChB,CAAC,CAAC;QACL,CAAC;KACF;CACF,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mtkn/mega-agent",
3
- "version": "0.4.0",
3
+ "version": "0.5.0",
4
4
  "description": "AI-powered agent infrastructure for Express + Prisma backends",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -52,7 +52,6 @@
52
52
  "@google/generative-ai": "^0.24.1",
53
53
  "@modelcontextprotocol/sdk": "^1.26.0",
54
54
  "@qdrant/js-client-rest": "^1.16.2",
55
- "bullmq": "^5.67.2",
56
55
  "openai": "^6.18.0",
57
56
  "winston": "^3.12.0",
58
57
  "zod": "^3.22.4"
@@ -1,8 +1,8 @@
1
1
  // ============================================================
2
- // @7style/mega-agent — Reference Prisma Schema
2
+ // @mtkn/mega-agent — Reference Prisma Schema
3
3
  // ============================================================
4
4
  //
5
- // Bu dosya @7style/mega-agent paketinin ihtiyaç duyduğu veritabanı
5
+ // Bu dosya @mtkn/mega-agent paketinin ihtiyaç duyduğu veritabanı
6
6
  // modellerini ve enum'larını dokümante eder.
7
7
  //
8
8
  // Host entegrasyonu için: npx mega-agent-prisma-sync --target prisma/schema.prisma