mcp-event-intelligence 0.1.1 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (31) hide show
  1. package/CHANGELOG.md +72 -0
  2. package/README.md +79 -4
  3. package/bin/mcp-event-intelligence.mjs +1 -1
  4. package/dist/src/composite/derivedGraph.d.ts +4 -0
  5. package/dist/src/composite/derivedGraph.js +46 -0
  6. package/dist/src/composite/engine.d.ts +3 -64
  7. package/dist/src/composite/engine.js +26 -343
  8. package/dist/src/composite/matching.d.ts +8 -0
  9. package/dist/src/composite/matching.js +109 -0
  10. package/dist/src/composite/runtimeSupport.d.ts +24 -0
  11. package/dist/src/composite/runtimeSupport.js +176 -0
  12. package/dist/src/composite/store.d.ts +59 -0
  13. package/dist/src/composite/store.js +1 -0
  14. package/dist/src/intelligenceProtocol/schemas.d.ts +9 -7
  15. package/dist/src/intelligenceProtocol/schemas.js +1 -0
  16. package/dist/src/intelligenceProtocol/triggerSchemas.d.ts +6 -6
  17. package/dist/src/mcpEvents/erpnextProvider.d.ts +20 -0
  18. package/dist/src/mcpEvents/erpnextProvider.js +80 -0
  19. package/package.json +5 -1
  20. package/scripts/host-integration.d.mts +34 -4
  21. package/scripts/host-integration.mjs +44 -1
  22. package/scripts/lib/composite-wake-coordinator.mjs +233 -9
  23. package/scripts/lib/event-processor.mjs +235 -20
  24. package/scripts/lib/local-event-intelligence-runtime.mjs +238 -83
  25. package/scripts/lib/mcp-events-client.mjs +184 -66
  26. package/scripts/lib/persistent-event-store.mjs +320 -1
  27. package/scripts/lib/temporal-deadline-scheduler.mjs +12 -2
  28. package/scripts/lib/wake-retry-scheduler.mjs +104 -0
  29. package/scripts/mcp-stdio-server.mjs +1 -1
  30. package/scripts/service.mjs +20 -0
  31. package/server.json +2 -2
@@ -0,0 +1,176 @@
1
+ import { sha256Hex } from '../intelligenceProtocol/canonical.js';
2
+ export class CompositeTriggerRuntimeSupport {
3
+ store;
4
+ now;
5
+ constructor(store, now = () => new Date()) {
6
+ this.store = store;
7
+ this.now = now;
8
+ }
9
+ async scheduleDeadlines(definition, record, deadlines) {
10
+ if (!this.store.putTemporalDeadline)
11
+ return;
12
+ for (const deadline of deadlines) {
13
+ const deadlineId = `td_${(await sha256Hex([
14
+ definition.triggerId,
15
+ definition.version,
16
+ record.matchId,
17
+ deadline.conditionId,
18
+ deadline.dueAt,
19
+ ].join(':'))).slice(0, 24)}`;
20
+ const existing = this.store.getTemporalDeadline?.(deadlineId);
21
+ if (existing?.status === 'pending' || existing?.status === 'fired') {
22
+ continue;
23
+ }
24
+ await this.store.putTemporalDeadline({
25
+ deadlineId,
26
+ triggerId: definition.triggerId,
27
+ triggerVersion: definition.version,
28
+ matchId: record.matchId,
29
+ conditionId: deadline.conditionId,
30
+ dueAt: deadline.dueAt,
31
+ status: 'pending',
32
+ });
33
+ }
34
+ }
35
+ async cancelDeadlinesForMatch(matchId) {
36
+ if (!this.store.listTemporalDeadlines ||
37
+ !this.store.setTemporalDeadlineStatus)
38
+ return;
39
+ const pending = this.store.listTemporalDeadlines({
40
+ matchId,
41
+ status: 'pending',
42
+ });
43
+ for (const deadline of pending) {
44
+ await this.store.setTemporalDeadlineStatus(deadline.deadlineId, 'cancelled');
45
+ }
46
+ }
47
+ async advanceLifecycleAfterEffect(match, effectKind, effectId) {
48
+ const definition = this.store.listTriggers().find((candidate) => candidate.triggerId === match.triggerId &&
49
+ candidate.version === match.triggerVersion);
50
+ const triggerState = this.store.getTriggerState?.(match.triggerId, match.triggerVersion) ?? null;
51
+ if (!definition || !this.store.setTriggerState)
52
+ return;
53
+ const previousCount = triggerState?.fireCount ?? 0;
54
+ const fireCount = previousCount + 1;
55
+ const lifecycle = definition.lifecycle ?? {};
56
+ const complete = lifecycle.oneShot === true ||
57
+ lifecycle.completeOnGoal === true ||
58
+ (lifecycle.maxFirings !== undefined &&
59
+ fireCount >= lifecycle.maxFirings);
60
+ const nextStatus = complete ? 'completed' : 'active';
61
+ const effectAt = this.now().toISOString();
62
+ await this.store.setTriggerState(match.triggerId, match.triggerVersion, nextStatus, {
63
+ type: 'system',
64
+ principal_id: 'event-intelligence:lifecycle',
65
+ }, {
66
+ owner: triggerState?.owner ?? null,
67
+ connectionIds: triggerState?.connectionIds ?? [],
68
+ fireCount,
69
+ lastFiredAt: effectAt,
70
+ });
71
+ if (complete) {
72
+ await this.auditTriggerLifecycle(definition, 'trigger.completed', {
73
+ reason: lifecycle.oneShot
74
+ ? 'one_shot'
75
+ : lifecycle.completeOnGoal
76
+ ? 'complete_on_goal'
77
+ : 'max_firings',
78
+ fireCount,
79
+ effectKind,
80
+ effectId,
81
+ });
82
+ }
83
+ }
84
+ async lifecycleAllows(definition, state, now) {
85
+ const lifecycle = definition.lifecycle ?? {};
86
+ const effectiveState = state ?? {
87
+ status: 'active',
88
+ fireCount: 0,
89
+ lastFiredAt: null,
90
+ connectionIds: [],
91
+ owner: null,
92
+ };
93
+ if (effectiveState.status !== 'active')
94
+ return false;
95
+ const expiresAt = lifecycle.expiresAt
96
+ ? Date.parse(lifecycle.expiresAt)
97
+ : Number.POSITIVE_INFINITY;
98
+ const leaseUntil = lifecycle.leaseUntil
99
+ ? Date.parse(lifecycle.leaseUntil)
100
+ : Number.POSITIVE_INFINITY;
101
+ if (now.getTime() > Math.min(expiresAt, leaseUntil)) {
102
+ if (this.store.setTriggerState) {
103
+ await this.store.setTriggerState(definition.triggerId, definition.version, 'expired', {
104
+ type: 'system',
105
+ principal_id: 'event-intelligence:lifecycle',
106
+ }, {
107
+ owner: effectiveState.owner ?? null,
108
+ connectionIds: effectiveState.connectionIds ?? [],
109
+ fireCount: effectiveState.fireCount ?? 0,
110
+ lastFiredAt: effectiveState.lastFiredAt ?? null,
111
+ });
112
+ }
113
+ await this.auditTriggerLifecycle(definition, 'trigger.lifecycle_expired', {
114
+ expiresAt: lifecycle.expiresAt ?? null,
115
+ leaseUntil: lifecycle.leaseUntil ?? null,
116
+ });
117
+ return false;
118
+ }
119
+ const fireCount = effectiveState.fireCount ?? 0;
120
+ if ((lifecycle.oneShot && fireCount >= 1) ||
121
+ (lifecycle.maxFirings !== undefined &&
122
+ fireCount >= lifecycle.maxFirings)) {
123
+ if (this.store.setTriggerState) {
124
+ await this.store.setTriggerState(definition.triggerId, definition.version, 'completed', {
125
+ type: 'system',
126
+ principal_id: 'event-intelligence:lifecycle',
127
+ }, {
128
+ owner: effectiveState.owner ?? null,
129
+ connectionIds: effectiveState.connectionIds ?? [],
130
+ fireCount,
131
+ lastFiredAt: effectiveState.lastFiredAt ?? null,
132
+ });
133
+ }
134
+ return false;
135
+ }
136
+ if (lifecycle.cooldownMs > 0 &&
137
+ effectiveState.lastFiredAt &&
138
+ now.getTime() - Date.parse(effectiveState.lastFiredAt) <
139
+ lifecycle.cooldownMs) {
140
+ return false;
141
+ }
142
+ return true;
143
+ }
144
+ async auditTriggerLifecycle(definition, kind, details) {
145
+ const timestamp = this.now().toISOString();
146
+ await this.store.appendAudit({
147
+ auditId: `audit_${(await sha256Hex(`${definition.triggerId}:${definition.version}:${kind}:${timestamp}`)).slice(0, 24)}`,
148
+ traceId: `trigger:${definition.triggerId}`,
149
+ timestamp,
150
+ kind,
151
+ entityType: 'trigger',
152
+ entityId: definition.triggerId,
153
+ details: {
154
+ triggerVersion: definition.version,
155
+ ...details,
156
+ },
157
+ });
158
+ }
159
+ async auditMatch(record, kind, details = {}) {
160
+ await this.store.appendAudit({
161
+ auditId: `audit_${(await sha256Hex(`${record.matchId}:${kind}:${record.updatedAt}:${this.store.listTriggerMatches().length}`)).slice(0, 24)}`,
162
+ traceId: record.sourceEvents[0]?.traceId ?? record.matchId,
163
+ timestamp: this.now().toISOString(),
164
+ kind,
165
+ entityType: 'trigger_match',
166
+ entityId: record.matchId,
167
+ details: {
168
+ triggerId: record.triggerId,
169
+ triggerVersion: record.triggerVersion,
170
+ status: record.status,
171
+ correlationKey: record.correlationKey,
172
+ ...details,
173
+ },
174
+ });
175
+ }
176
+ }
@@ -0,0 +1,59 @@
1
+ import type { CompositeTriggerDefinition, TriggerMatchRecord } from '../intelligenceProtocol/triggerSchemas.js';
2
+ export interface CompositeTriggerStore {
3
+ putTrigger(definition: CompositeTriggerDefinition): Promise<void>;
4
+ listTriggers(): CompositeTriggerDefinition[];
5
+ getTriggerState?(triggerId: string, version: string): {
6
+ status: 'active' | 'paused' | 'completed' | 'expired' | 'deleted';
7
+ owner?: unknown;
8
+ connectionIds?: string[];
9
+ fireCount?: number;
10
+ lastFiredAt?: string | null;
11
+ revision?: number;
12
+ } | null;
13
+ setTriggerState?(triggerId: string, version: string, status: 'active' | 'paused' | 'completed' | 'expired' | 'deleted', actor?: unknown, metadata?: Record<string, unknown>): Promise<unknown>;
14
+ appendTriggerMatch(record: TriggerMatchRecord): Promise<void>;
15
+ listTriggerMatches(triggerId?: string): TriggerMatchRecord[];
16
+ getTemporalDeadline?(deadlineId: string): {
17
+ deadlineId: string;
18
+ triggerId: string;
19
+ triggerVersion: string;
20
+ matchId: string;
21
+ conditionId: string;
22
+ dueAt: string;
23
+ status: 'pending' | 'cancelled' | 'fired';
24
+ } | null;
25
+ listTemporalDeadlines?(filter?: {
26
+ triggerId?: string;
27
+ matchId?: string;
28
+ status?: string;
29
+ }): Array<{
30
+ deadlineId: string;
31
+ triggerId: string;
32
+ triggerVersion: string;
33
+ matchId: string;
34
+ conditionId: string;
35
+ dueAt: string;
36
+ status: string;
37
+ }>;
38
+ putTemporalDeadline?(input: {
39
+ deadlineId: string;
40
+ triggerId: string;
41
+ triggerVersion: string;
42
+ matchId: string;
43
+ conditionId: string;
44
+ dueAt: string;
45
+ status: 'pending' | 'cancelled' | 'fired';
46
+ }): Promise<unknown>;
47
+ setTemporalDeadlineStatus?(deadlineId: string, status: 'pending' | 'cancelled' | 'fired'): Promise<unknown>;
48
+ }
49
+ export interface CompositeTriggerAudit {
50
+ appendAudit(input: {
51
+ auditId: string;
52
+ traceId: string;
53
+ timestamp: string;
54
+ kind: string;
55
+ entityType: 'trigger_match' | 'trigger';
56
+ entityId: string;
57
+ details?: Record<string, unknown>;
58
+ }): Promise<unknown>;
59
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -68,8 +68,8 @@ export declare const SemanticDecisionRecordSchema: z.ZodObject<{
68
68
  createdAt: z.ZodString;
69
69
  evaluator: z.ZodString;
70
70
  outcome: z.ZodEnum<{
71
- reject: "reject";
72
71
  match: "match";
72
+ reject: "reject";
73
73
  uncertain: "uncertain";
74
74
  }>;
75
75
  probability: z.ZodNumber;
@@ -79,9 +79,9 @@ export declare const SemanticDecisionRecordSchema: z.ZodObject<{
79
79
  matchThreshold: z.ZodNumber;
80
80
  rejectThreshold: z.ZodNumber;
81
81
  uncertain: z.ZodEnum<{
82
- escalate: "escalate";
83
- reject: "reject";
84
82
  match: "match";
83
+ reject: "reject";
84
+ escalate: "escalate";
85
85
  }>;
86
86
  }, z.core.$strip>;
87
87
  inputFields: z.ZodArray<z.ZodString>;
@@ -136,9 +136,9 @@ export declare const SemanticConditionWireSchema: z.ZodObject<{
136
136
  matchThreshold: z.ZodNumber;
137
137
  rejectThreshold: z.ZodNumber;
138
138
  uncertain: z.ZodEnum<{
139
- escalate: "escalate";
140
- reject: "reject";
141
139
  match: "match";
140
+ reject: "reject";
141
+ escalate: "escalate";
142
142
  }>;
143
143
  }, z.core.$strip>;
144
144
  export declare const EventIngestRequestSchema: z.ZodObject<{
@@ -181,9 +181,9 @@ export declare const EventIngestRequestSchema: z.ZodObject<{
181
181
  matchThreshold: z.ZodNumber;
182
182
  rejectThreshold: z.ZodNumber;
183
183
  uncertain: z.ZodEnum<{
184
- escalate: "escalate";
185
- reject: "reject";
186
184
  match: "match";
185
+ reject: "reject";
186
+ escalate: "escalate";
187
187
  }>;
188
188
  }, z.core.$strip>>;
189
189
  wakeOnEscalation: z.ZodDefault<z.ZodBoolean>;
@@ -209,6 +209,7 @@ export declare const AuditKindSchema: z.ZodEnum<{
209
209
  "lifecycle.transition": "lifecycle.transition";
210
210
  "wake.queued": "wake.queued";
211
211
  "wake.delivered": "wake.delivered";
212
+ "wake.retry_scheduled": "wake.retry_scheduled";
212
213
  "wake.handled": "wake.handled";
213
214
  "wake.dead_letter": "wake.dead_letter";
214
215
  "trigger.partial": "trigger.partial";
@@ -244,6 +245,7 @@ export declare const AuditRecordSchema: z.ZodObject<{
244
245
  "lifecycle.transition": "lifecycle.transition";
245
246
  "wake.queued": "wake.queued";
246
247
  "wake.delivered": "wake.delivered";
248
+ "wake.retry_scheduled": "wake.retry_scheduled";
247
249
  "wake.handled": "wake.handled";
248
250
  "wake.dead_letter": "wake.dead_letter";
249
251
  "trigger.partial": "trigger.partial";
@@ -117,6 +117,7 @@ export const AuditKindSchema = z.enum([
117
117
  'lifecycle.transition',
118
118
  'wake.queued',
119
119
  'wake.delivered',
120
+ 'wake.retry_scheduled',
120
121
  'wake.handled',
121
122
  'wake.dead_letter',
122
123
  'trigger.partial',
@@ -182,9 +182,9 @@ export declare const SemanticCorrelationSchema: z.ZodObject<{
182
182
  matchThreshold: z.ZodNumber;
183
183
  rejectThreshold: z.ZodNumber;
184
184
  uncertain: z.ZodDefault<z.ZodEnum<{
185
- escalate: "escalate";
186
- reject: "reject";
187
185
  match: "match";
186
+ reject: "reject";
187
+ escalate: "escalate";
188
188
  }>>;
189
189
  }, z.core.$strip>;
190
190
  export declare const CompositeTriggerDefinitionSchema: z.ZodObject<{
@@ -320,9 +320,9 @@ export declare const CompositeTriggerDefinitionSchema: z.ZodObject<{
320
320
  matchThreshold: z.ZodNumber;
321
321
  rejectThreshold: z.ZodNumber;
322
322
  uncertain: z.ZodDefault<z.ZodEnum<{
323
- escalate: "escalate";
324
- reject: "reject";
325
323
  match: "match";
324
+ reject: "reject";
325
+ escalate: "escalate";
326
326
  }>>;
327
327
  }, z.core.$strip>>;
328
328
  }, z.core.$strip>>;
@@ -408,8 +408,8 @@ export declare const TriggerSourceEventSchema: z.ZodObject<{
408
408
  export declare const CompositeCorrelationDecisionSchema: z.ZodObject<{
409
409
  evaluator: z.ZodString;
410
410
  outcome: z.ZodEnum<{
411
- reject: "reject";
412
411
  match: "match";
412
+ reject: "reject";
413
413
  uncertain: "uncertain";
414
414
  }>;
415
415
  probability: z.ZodNumber;
@@ -457,8 +457,8 @@ export declare const TriggerMatchRecordSchema: z.ZodObject<{
457
457
  correlationDecision: z.ZodNullable<z.ZodObject<{
458
458
  evaluator: z.ZodString;
459
459
  outcome: z.ZodEnum<{
460
- reject: "reject";
461
460
  match: "match";
461
+ reject: "reject";
462
462
  uncertain: "uncertain";
463
463
  }>;
464
464
  probability: z.ZodNumber;
@@ -0,0 +1,20 @@
1
+ import { type McpEventsProvider, type ProviderPollRequest } from './provider.js';
2
+ export type ErpNextEventName = 'erpnext.sales_invoice.submitted' | 'erpnext.sales_order.created';
3
+ export interface ErpNextProviderPollResult {
4
+ events: Array<{
5
+ eventId: string;
6
+ timestamp: string;
7
+ data: Record<string, unknown>;
8
+ }>;
9
+ cursor: string;
10
+ hasMore?: boolean;
11
+ nextPollMs?: number;
12
+ }
13
+ export type ErpNextEventPoller<TContext = unknown> = (request: ProviderPollRequest<TContext>) => ErpNextProviderPollResult | Promise<ErpNextProviderPollResult>;
14
+ export interface CreateErpNextEventsProviderOptions<TContext = unknown> {
15
+ pollSalesInvoices: ErpNextEventPoller<TContext>;
16
+ pollSalesOrders: ErpNextEventPoller<TContext>;
17
+ supportedVersions?: string[];
18
+ instructions?: string;
19
+ }
20
+ export declare function createErpNextEventsProvider<TContext = unknown>(options: CreateErpNextEventsProviderOptions<TContext>): McpEventsProvider<TContext>;
@@ -0,0 +1,80 @@
1
+ import { createMcpEventsProvider, } from './provider.js';
2
+ function toOccurrences(name, result) {
3
+ return result.events.map((event) => ({
4
+ eventId: String(event.eventId),
5
+ name,
6
+ timestamp: String(event.timestamp),
7
+ data: event.data,
8
+ }));
9
+ }
10
+ export function createErpNextEventsProvider(options) {
11
+ if (!options || typeof options.pollSalesInvoices !== 'function') {
12
+ throw new Error('ERPNext Events provider requires pollSalesInvoices()');
13
+ }
14
+ if (typeof options.pollSalesOrders !== 'function') {
15
+ throw new Error('ERPNext Events provider requires pollSalesOrders()');
16
+ }
17
+ return createMcpEventsProvider({
18
+ supportedVersions: options.supportedVersions,
19
+ instructions: options.instructions ??
20
+ 'ERPNext MCP Events adapter exposing host-owned Sales Invoice and Sales Order changes.',
21
+ events: [
22
+ {
23
+ descriptor: {
24
+ name: 'erpnext.sales_invoice.submitted',
25
+ description: 'A Sales Invoice reached submitted status in ERPNext.',
26
+ delivery: ['poll'],
27
+ inputSchema: {},
28
+ payloadSchema: {
29
+ type: 'object',
30
+ required: ['name'],
31
+ properties: {
32
+ name: { type: 'string', minLength: 1 },
33
+ company: { type: 'string' },
34
+ customer: { type: 'string' },
35
+ grand_total: { type: 'number' },
36
+ currency: { type: 'string' },
37
+ },
38
+ },
39
+ },
40
+ poll: async (request) => {
41
+ const result = await options.pollSalesInvoices(request);
42
+ return {
43
+ events: toOccurrences('erpnext.sales_invoice.submitted', result),
44
+ cursor: result.cursor,
45
+ hasMore: result.hasMore ?? false,
46
+ nextPollMs: result.nextPollMs ?? 5000,
47
+ };
48
+ },
49
+ },
50
+ {
51
+ descriptor: {
52
+ name: 'erpnext.sales_order.created',
53
+ description: 'A Sales Order was created in ERPNext.',
54
+ delivery: ['poll'],
55
+ inputSchema: {},
56
+ payloadSchema: {
57
+ type: 'object',
58
+ required: ['name'],
59
+ properties: {
60
+ name: { type: 'string', minLength: 1 },
61
+ company: { type: 'string' },
62
+ customer: { type: 'string' },
63
+ grand_total: { type: 'number' },
64
+ currency: { type: 'string' },
65
+ },
66
+ },
67
+ },
68
+ poll: async (request) => {
69
+ const result = await options.pollSalesOrders(request);
70
+ return {
71
+ events: toOccurrences('erpnext.sales_order.created', result),
72
+ cursor: result.cursor,
73
+ hasMore: result.hasMore ?? false,
74
+ nextPollMs: result.nextPollMs ?? 5000,
75
+ };
76
+ },
77
+ },
78
+ ],
79
+ });
80
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mcp-event-intelligence",
3
- "version": "0.1.1",
3
+ "version": "0.2.1",
4
4
  "description": "Durable temporal event intelligence for agent hosts: host-owned MCP event discovery, composite triggers, derived events, and targeted wakeups.",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",
@@ -18,6 +18,10 @@
18
18
  "./provider": {
19
19
  "types": "./dist/src/mcpEvents/provider.d.ts",
20
20
  "import": "./dist/src/mcpEvents/provider.js"
21
+ },
22
+ "./provider/erpnext": {
23
+ "types": "./dist/src/mcpEvents/erpnextProvider.d.ts",
24
+ "import": "./dist/src/mcpEvents/erpnextProvider.js"
21
25
  }
22
26
  },
23
27
  "bin": {
@@ -14,8 +14,12 @@ export interface HostMcpConnectionOptions {
14
14
  client?: HostMcpClientLike;
15
15
  request?: (method: string, params?: unknown) => Promise<unknown>;
16
16
  enabled?: boolean;
17
+ /** Isolation partition used by the shared EI host. Defaults to \"default\". */
18
+ scopeId?: string;
17
19
  pollIntervalMs?: number;
18
20
  maxEvents?: number;
21
+ /** Maximum number of immediately drained pages when the provider reports hasMore. */
22
+ maxPollBatches?: number;
19
23
  }
20
24
 
21
25
  export interface HostMcpRegistry {
@@ -36,8 +40,18 @@ export type HostWakeHandler = (
36
40
  packet: Record<string, unknown>,
37
41
  ) => Promise<HostWakeReceipt | string> | HostWakeReceipt | string;
38
42
 
43
+ export interface EventIntelligenceStore {
44
+ init?(): Promise<unknown>;
45
+ /** Required when non-default scopes are used. Implementations should return an isolated store view. */
46
+ forScope?(scopeId: string): Promise<EventIntelligenceStore> | EventIntelligenceStore;
47
+ listScopeIds?(): Promise<string[]> | string[];
48
+ [key: string]: any;
49
+ }
50
+
39
51
  export interface EventIntelligenceHostOptions {
40
52
  dataDir?: string;
53
+ /** Optional storage backend. PersistentEventStore is used when omitted. */
54
+ store?: EventIntelligenceStore;
41
55
  env?: Record<string, string | undefined>;
42
56
  mcpRegistry?: HostMcpRegistry;
43
57
  /** Low-level/manual fallback; prefer mcpRegistry for automatic discovery. */
@@ -49,19 +63,25 @@ export interface EventIntelligenceHostOptions {
49
63
  semanticEvaluator?: unknown;
50
64
  }
51
65
 
52
- export interface EventIntelligenceHost {
66
+ export interface EventIntelligenceScopedHost {
67
+ readonly scopeId: string;
53
68
  readonly runtime: any;
54
- readonly store: any;
69
+ readonly store: EventIntelligenceStore;
55
70
  readonly triggerControl: any;
56
71
  readonly triggerInspector: any;
57
72
  readonly eventSources: any[];
58
- refreshMcpRegistry(): Promise<any[]>;
59
73
  attachMcpClient(connection: HostMcpConnectionOptions): Promise<{
60
74
  connectionId: string;
61
75
  events: any[];
62
76
  }>;
63
- detachMcpClient(connectionId: string): Promise<boolean>;
64
77
  mcpStatus(): any[];
78
+ }
79
+
80
+ export interface EventIntelligenceHost extends EventIntelligenceScopedHost {
81
+ refreshMcpRegistry(): Promise<any[]>;
82
+ detachMcpClient(connectionId: string): Promise<boolean>;
83
+ loadedScopes(): string[];
84
+ scope(scopeId?: string): Promise<EventIntelligenceScopedHost>;
65
85
  close(): Promise<void>;
66
86
  }
67
87
 
@@ -84,3 +104,13 @@ export function createHostMcpEventsConnection(
84
104
  export function createEventIntelligenceHost(
85
105
  options?: EventIntelligenceHostOptions,
86
106
  ): Promise<EventIntelligenceHost>;
107
+
108
+
109
+ export class PersistentEventStore implements EventIntelligenceStore {
110
+ constructor(dataDir: string);
111
+ readonly dataDir: string;
112
+ init(): Promise<unknown>;
113
+ forScope(scopeId?: string): Promise<PersistentEventStore>;
114
+ listScopeIds(): Promise<string[]>;
115
+ [key: string]: any;
116
+ }
@@ -4,6 +4,11 @@ import {
4
4
  import {
5
5
  createHostMcpEventsConnection,
6
6
  } from './lib/mcp-events-client.mjs';
7
+ import {
8
+ DEFAULT_EVENT_SCOPE_ID,
9
+ PersistentEventStore,
10
+ normalizeEventScopeId,
11
+ } from './lib/persistent-event-store.mjs';
7
12
 
8
13
  function normalizeMcpConnection(input) {
9
14
  const connectionId = String(
@@ -61,6 +66,31 @@ export function createMcpRegistryAdapter({
61
66
  };
62
67
  }
63
68
 
69
+ function scopedHostView(runtime, context) {
70
+ const scopeId = context.scopeId;
71
+ return {
72
+ scopeId,
73
+ runtime: context,
74
+ store: context.store,
75
+ triggerControl: context.triggerControl,
76
+ triggerInspector: context.triggerInspector,
77
+ get eventSources() {
78
+ return context.triggerControl.listEventSources();
79
+ },
80
+ async attachMcpClient(connection) {
81
+ const normalized = normalizeMcpConnection({
82
+ ...connection,
83
+ scopeId,
84
+ });
85
+ return runtime.mcpEventsClient.attachConnection(normalized);
86
+ },
87
+ mcpStatus() {
88
+ return runtime.mcpEventsClient.status()
89
+ .filter((entry) => entry.scopeId === scopeId);
90
+ },
91
+ };
92
+ }
93
+
64
94
  /**
65
95
  * Embed Event Intelligence once at the harness/host level.
66
96
  *
@@ -70,6 +100,7 @@ export function createMcpRegistryAdapter({
70
100
  */
71
101
  export async function createEventIntelligenceHost({
72
102
  dataDir,
103
+ store,
73
104
  env = {},
74
105
  mcpRegistry,
75
106
  mcpClients = [],
@@ -88,6 +119,7 @@ export async function createEventIntelligenceHost({
88
119
  wake,
89
120
  wakeHandlers,
90
121
  semanticEvaluator,
122
+ store,
91
123
  });
92
124
 
93
125
  const registryManaged = new Set();
@@ -117,7 +149,8 @@ export async function createEventIntelligenceHost({
117
149
  if (existing) {
118
150
  if (
119
151
  existing.identity === connection.identity &&
120
- existing.serverId === connection.serverId
152
+ existing.serverId === connection.serverId &&
153
+ existing.scopeId === connection.scopeId
121
154
  ) {
122
155
  registryManaged.add(connectionId);
123
156
  outcomes.push({ connectionId, status: 'already_attached' });
@@ -179,6 +212,7 @@ export async function createEventIntelligenceHost({
179
212
  }
180
213
 
181
214
  return {
215
+ scopeId: DEFAULT_EVENT_SCOPE_ID,
182
216
  runtime,
183
217
  get store() {
184
218
  return runtime.store;
@@ -204,6 +238,14 @@ export async function createEventIntelligenceHost({
204
238
  mcpStatus() {
205
239
  return runtime.mcpEventsClient.status();
206
240
  },
241
+ loadedScopes() {
242
+ return runtime.loadedScopes();
243
+ },
244
+ async scope(scopeIdInput = DEFAULT_EVENT_SCOPE_ID) {
245
+ const scopeId = normalizeEventScopeId(scopeIdInput);
246
+ const context = await runtime.scope(scopeId);
247
+ return scopedHostView(runtime, context);
248
+ },
207
249
  async close() {
208
250
  unsubscribe?.();
209
251
  await runtime.close();
@@ -213,4 +255,5 @@ export async function createEventIntelligenceHost({
213
255
 
214
256
  export {
215
257
  createHostMcpEventsConnection,
258
+ PersistentEventStore,
216
259
  };