@auxdynamics/mastguard-agent-sdk 0.1.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 AuxDynamics Inc.
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,140 @@
1
+ # @auxdynamics/mastguard-agent-sdk
2
+
3
+ > Runtime AI security SDK for MastGuard — wraps any LLM call with prompt injection detection, scope enforcement, and tamper-evident audit logging.
4
+
5
+ [![npm version](https://img.shields.io/npm/v/@auxdynamics/mastguard-agent-sdk)](https://www.npmjs.com/package/@auxdynamics/mastguard-agent-sdk)
6
+ [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE)
7
+
8
+ ## Installation
9
+
10
+ ```bash
11
+ npm install @auxdynamics/mastguard-agent-sdk
12
+ ```
13
+
14
+ ## Quickstart
15
+
16
+ ```ts
17
+ import { MastGuardShield } from '@auxdynamics/mastguard-agent-sdk';
18
+
19
+ const shield = new MastGuardShield({
20
+ apiKey: process.env.MASTGUARD_API_KEY,
21
+ policy: 'standard',
22
+ agentId: 'my-customer-support-bot',
23
+ organizationId: 'org-abc123',
24
+ });
25
+
26
+ const response = await shield.protect(
27
+ openai.chat.completions.create({ model: 'gpt-4o', messages }),
28
+ { sessionId: req.user.id, toolCalls: pendingToolCalls }
29
+ );
30
+
31
+ if (!response.allowed) {
32
+ console.log('Blocked:', response.violations);
33
+ }
34
+ ```
35
+
36
+ ## Authentication
37
+
38
+ Get your API key from **[https://dashboard.mastguard.io](https://dashboard.mastguard.io) → Settings → API Keys**.
39
+
40
+ Pass it as `apiKey` in `ShieldConfig` or set the `MASTGUARD_API_KEY` environment variable. All requests use the `X-API-Key` header.
41
+
42
+ ## Configuration
43
+
44
+ | Option | Type | Required | Default | Description |
45
+ | ---------------- | ---------------------- | -------- | ---------------------------- | --------------------------------------------------------- |
46
+ | `apiKey` | `string` | Yes | — | MastGuard API key from dashboard |
47
+ | `policy` | `string` | Yes | — | Policy name: `standard`, `hipaa`, or `enterprise` |
48
+ | `agentId` | `string` | Yes | — | Unique identifier for this agent |
49
+ | `organizationId` | `string` | Yes | — | Your MastGuard organization ID |
50
+ | `endpoint` | `string` | No | `https://api.mastguard.io` | Override API base URL (staging / self-hosted) |
51
+ | `mode` | `'block' \| 'monitor'` | No | `'block'` | `block` enforces policy; `monitor` logs only |
52
+ | `timeout` | `number` | No | `3000` | Ingest API timeout in milliseconds |
53
+
54
+ ## Shield Methods
55
+
56
+ ### `shield.protect(llmCall, options)`
57
+
58
+ Wraps any LLM call — evaluates the request and response against your configured policy.
59
+
60
+ ```ts
61
+ const result = await shield.protect(
62
+ openai.chat.completions.create({ model: 'gpt-4o', messages }),
63
+ {
64
+ sessionId: 'session-xyz', // required — ties events to a session
65
+ toolCalls: [...], // optional — pending tool calls to inspect
66
+ userId: 'user-123', // optional — for per-user audit trails
67
+ metadata: { env: 'prod' }, // optional — attached to audit records
68
+ }
69
+ );
70
+ ```
71
+
72
+ **Returns** `ShieldResult<T>`:
73
+
74
+ | Field | Type | Description |
75
+ | ------------ | -------------------- | ------------------------------------------------ |
76
+ | `data` | `T \| null` | The original LLM response (null if blocked) |
77
+ | `allowed` | `boolean` | `true` if the call passed all policy checks |
78
+ | `violations` | `ViolationRecord[]` | List of policy violations found (empty if clean) |
79
+ | `auditId` | `string \| undefined`| Tamper-evident audit record ID |
80
+ | `sessionId` | `string` | Session ID echoed back for correlation |
81
+
82
+ ## Detection Layers
83
+
84
+ | Layer | Rule ID | What It Detects | Research Basis |
85
+ | ------------------ | ----------------- | ---------------------------------------------------------- | ---------------- |
86
+ | Prompt Injection | `RULE-INJ-001` | Direct instruction-override attempts in user input | arXiv:2510.22620 |
87
+ | Indirect Injection | `RULE-INJ-002` | Instructions embedded in tool outputs or RAG results | arXiv:2510.22620 |
88
+ | Scope Violation | `RULE-SCOPE-001` | Tool calls outside the agent's declared policy | arXiv:2510.22620 |
89
+ | Data Exfiltration | `RULE-EXFIL-PII-*`| PII, credentials, API keys in LLM responses | arXiv:2510.22620 |
90
+ | Multi-Step Attack | `RULE-CHAIN-001` | Sequential tool calls matching known attack chains | arXiv:2603.11214 |
91
+
92
+ All detections are run by `ThreatDetector` and evaluated against your policy by `PolicyEngine`. Events are logged via `AuditLogger` with SHA-256 chain hashing for tamper evidence.
93
+
94
+ ## Error Handling
95
+
96
+ ```ts
97
+ const result = await shield.protect(llmCall, { sessionId });
98
+
99
+ if (!result.allowed) {
100
+ for (const v of result.violations) {
101
+ console.error(`[${v.severity}] ${v.category}: ${v.description}`);
102
+ // v.action is 'block' | 'flag' | 'log'
103
+ // v.evidence contains the raw matched content
104
+ }
105
+ // result.data is null when mode === 'block' and violations were found
106
+ }
107
+ ```
108
+
109
+ In `monitor` mode, `allowed` is always `true` — violations are logged to MastGuard but the call is never blocked, letting you evaluate policy impact before enforcing it.
110
+
111
+ ## TypeScript
112
+
113
+ Full TypeScript support is included — no `@types` package needed. CJS and ESM builds are both shipped.
114
+
115
+ ```ts
116
+ import type {
117
+ ShieldConfig,
118
+ ShieldResult,
119
+ ViolationRecord,
120
+ ToolCallRecord,
121
+ ProtectOptions,
122
+ EvaluationResult,
123
+ PolicyTier,
124
+ ShieldMode,
125
+ Severity,
126
+ ViolationAction,
127
+ } from '@auxdynamics/mastguard-agent-sdk';
128
+ ```
129
+
130
+ ## Related Packages
131
+
132
+ This package handles **runtime AI security monitoring**.
133
+
134
+ If you need to integrate with the MastGuard **governance platform** (audit logs, HITL queues, webhooks, compliance dashboards), use the companion SDK:
135
+
136
+ [@auxdynamics/mastguard-sdk](https://www.npmjs.com/package/@auxdynamics/mastguard-sdk)
137
+
138
+ ## License
139
+
140
+ MIT © [AuxDynamics Inc.](https://mastguard.io)
@@ -0,0 +1,129 @@
1
+ type Severity = 'critical' | 'high' | 'medium' | 'low' | 'info';
2
+ type ViolationAction = 'block' | 'flag' | 'log';
3
+ type EventType = 'prompt_injection' | 'scope_violation' | 'data_exfiltration' | 'multi_step_attack' | 'normal';
4
+ type ShieldMode = 'block' | 'monitor';
5
+ type PolicyTier = 'standard' | 'hipaa' | 'enterprise';
6
+ interface ViolationRecord {
7
+ category: string;
8
+ severity: Severity;
9
+ description: string;
10
+ action: ViolationAction;
11
+ evidence: string;
12
+ }
13
+ interface ShieldConfig {
14
+ apiKey: string;
15
+ organizationId: string;
16
+ agentId: string;
17
+ policy?: string;
18
+ mode?: ShieldMode;
19
+ apiBaseUrl?: string;
20
+ timeoutMs?: number;
21
+ }
22
+ interface ToolCall {
23
+ name: string;
24
+ parameters?: Record<string, unknown>;
25
+ }
26
+ interface TurnRecord {
27
+ role: 'user' | 'assistant' | 'tool';
28
+ content: string;
29
+ toolCalls?: ToolCall[];
30
+ }
31
+ interface ProtectOptions {
32
+ sessionId: string;
33
+ toolCalls?: ToolCall[];
34
+ toolOutputs?: string[];
35
+ sessionHistory?: TurnRecord[];
36
+ tokenCount?: number;
37
+ }
38
+ interface ShieldResult<T> {
39
+ data: T | null;
40
+ allowed: boolean;
41
+ violations: ViolationRecord[];
42
+ auditId?: string;
43
+ }
44
+ interface DetectOptions {
45
+ prompt: string;
46
+ response?: string;
47
+ toolCalls?: ToolCall[];
48
+ toolOutputs?: string[];
49
+ sessionHistory?: TurnRecord[];
50
+ allowedTools?: string[];
51
+ tokenCount?: number;
52
+ }
53
+ interface EvaluationResult {
54
+ violations: ViolationRecord[];
55
+ allow: boolean;
56
+ worstSeverity: Severity | null;
57
+ }
58
+
59
+ declare class MastGuardShield {
60
+ private readonly config;
61
+ private readonly sessionTracker;
62
+ private readonly policyEngine;
63
+ private readonly auditLogger;
64
+ constructor(config: ShieldConfig);
65
+ protect<T>(llmCall: Promise<T>, options: ProtectOptions): Promise<ShieldResult<T>>;
66
+ clearSession(sessionId: string): void;
67
+ invalidatePolicyCache(): void;
68
+ }
69
+
70
+ declare class ThreatDetector {
71
+ static detect(options: DetectOptions): EvaluationResult;
72
+ private static detectPromptInjection;
73
+ private static detectScopeViolation;
74
+ private static detectDataExfiltration;
75
+ private static detectIndirectInjection;
76
+ private static detectMultiStepAttack;
77
+ }
78
+
79
+ interface IngestPayload {
80
+ session_id: string;
81
+ agent_id: string;
82
+ org_id: string;
83
+ policy_id: string | null;
84
+ event_type: string;
85
+ prompt: string;
86
+ response: string | null;
87
+ tool_calls: Array<{
88
+ name: string;
89
+ parameters?: Record<string, unknown> | undefined;
90
+ }>;
91
+ tool_outputs: string[];
92
+ session_history: Array<{
93
+ role: string;
94
+ content: string;
95
+ }>;
96
+ token_count: number;
97
+ duration_ms: number;
98
+ }
99
+ declare class AuditLogger {
100
+ private readonly config;
101
+ constructor(config: ShieldConfig);
102
+ static computeChainHash(prevHash: string | null, contentJson: string, salt: string): string;
103
+ static verifyChain(entries: Array<{
104
+ content: string;
105
+ hash: string;
106
+ }>, salt: string): boolean;
107
+ ingest(payload: IngestPayload): Promise<string | null>;
108
+ }
109
+
110
+ declare class PolicyEngine {
111
+ private readonly config;
112
+ private policyCache;
113
+ constructor(config: ShieldConfig);
114
+ evaluate(options: DetectOptions, policyName: string): Promise<EvaluationResult>;
115
+ private fetchPolicy;
116
+ invalidateCache(): void;
117
+ }
118
+
119
+ declare class SessionTracker {
120
+ private sessions;
121
+ addTurn(sessionId: string, turn: TurnRecord): void;
122
+ getHistory(sessionId: string): TurnRecord[];
123
+ getToolCallSequence(sessionId: string): string[];
124
+ clearSession(sessionId: string): void;
125
+ getSessionCount(): number;
126
+ pruneOldSessions(maxAgeMs?: number): void;
127
+ }
128
+
129
+ export { AuditLogger, type DetectOptions, type EvaluationResult, type EventType, MastGuardShield, PolicyEngine, type PolicyTier, type ProtectOptions, SessionTracker, type Severity, type ShieldConfig, type ShieldMode, type ShieldResult, ThreatDetector, type ToolCall, type TurnRecord, type ViolationAction, type ViolationRecord };
@@ -0,0 +1,129 @@
1
+ type Severity = 'critical' | 'high' | 'medium' | 'low' | 'info';
2
+ type ViolationAction = 'block' | 'flag' | 'log';
3
+ type EventType = 'prompt_injection' | 'scope_violation' | 'data_exfiltration' | 'multi_step_attack' | 'normal';
4
+ type ShieldMode = 'block' | 'monitor';
5
+ type PolicyTier = 'standard' | 'hipaa' | 'enterprise';
6
+ interface ViolationRecord {
7
+ category: string;
8
+ severity: Severity;
9
+ description: string;
10
+ action: ViolationAction;
11
+ evidence: string;
12
+ }
13
+ interface ShieldConfig {
14
+ apiKey: string;
15
+ organizationId: string;
16
+ agentId: string;
17
+ policy?: string;
18
+ mode?: ShieldMode;
19
+ apiBaseUrl?: string;
20
+ timeoutMs?: number;
21
+ }
22
+ interface ToolCall {
23
+ name: string;
24
+ parameters?: Record<string, unknown>;
25
+ }
26
+ interface TurnRecord {
27
+ role: 'user' | 'assistant' | 'tool';
28
+ content: string;
29
+ toolCalls?: ToolCall[];
30
+ }
31
+ interface ProtectOptions {
32
+ sessionId: string;
33
+ toolCalls?: ToolCall[];
34
+ toolOutputs?: string[];
35
+ sessionHistory?: TurnRecord[];
36
+ tokenCount?: number;
37
+ }
38
+ interface ShieldResult<T> {
39
+ data: T | null;
40
+ allowed: boolean;
41
+ violations: ViolationRecord[];
42
+ auditId?: string;
43
+ }
44
+ interface DetectOptions {
45
+ prompt: string;
46
+ response?: string;
47
+ toolCalls?: ToolCall[];
48
+ toolOutputs?: string[];
49
+ sessionHistory?: TurnRecord[];
50
+ allowedTools?: string[];
51
+ tokenCount?: number;
52
+ }
53
+ interface EvaluationResult {
54
+ violations: ViolationRecord[];
55
+ allow: boolean;
56
+ worstSeverity: Severity | null;
57
+ }
58
+
59
+ declare class MastGuardShield {
60
+ private readonly config;
61
+ private readonly sessionTracker;
62
+ private readonly policyEngine;
63
+ private readonly auditLogger;
64
+ constructor(config: ShieldConfig);
65
+ protect<T>(llmCall: Promise<T>, options: ProtectOptions): Promise<ShieldResult<T>>;
66
+ clearSession(sessionId: string): void;
67
+ invalidatePolicyCache(): void;
68
+ }
69
+
70
+ declare class ThreatDetector {
71
+ static detect(options: DetectOptions): EvaluationResult;
72
+ private static detectPromptInjection;
73
+ private static detectScopeViolation;
74
+ private static detectDataExfiltration;
75
+ private static detectIndirectInjection;
76
+ private static detectMultiStepAttack;
77
+ }
78
+
79
+ interface IngestPayload {
80
+ session_id: string;
81
+ agent_id: string;
82
+ org_id: string;
83
+ policy_id: string | null;
84
+ event_type: string;
85
+ prompt: string;
86
+ response: string | null;
87
+ tool_calls: Array<{
88
+ name: string;
89
+ parameters?: Record<string, unknown> | undefined;
90
+ }>;
91
+ tool_outputs: string[];
92
+ session_history: Array<{
93
+ role: string;
94
+ content: string;
95
+ }>;
96
+ token_count: number;
97
+ duration_ms: number;
98
+ }
99
+ declare class AuditLogger {
100
+ private readonly config;
101
+ constructor(config: ShieldConfig);
102
+ static computeChainHash(prevHash: string | null, contentJson: string, salt: string): string;
103
+ static verifyChain(entries: Array<{
104
+ content: string;
105
+ hash: string;
106
+ }>, salt: string): boolean;
107
+ ingest(payload: IngestPayload): Promise<string | null>;
108
+ }
109
+
110
+ declare class PolicyEngine {
111
+ private readonly config;
112
+ private policyCache;
113
+ constructor(config: ShieldConfig);
114
+ evaluate(options: DetectOptions, policyName: string): Promise<EvaluationResult>;
115
+ private fetchPolicy;
116
+ invalidateCache(): void;
117
+ }
118
+
119
+ declare class SessionTracker {
120
+ private sessions;
121
+ addTurn(sessionId: string, turn: TurnRecord): void;
122
+ getHistory(sessionId: string): TurnRecord[];
123
+ getToolCallSequence(sessionId: string): string[];
124
+ clearSession(sessionId: string): void;
125
+ getSessionCount(): number;
126
+ pruneOldSessions(maxAgeMs?: number): void;
127
+ }
128
+
129
+ export { AuditLogger, type DetectOptions, type EvaluationResult, type EventType, MastGuardShield, PolicyEngine, type PolicyTier, type ProtectOptions, SessionTracker, type Severity, type ShieldConfig, type ShieldMode, type ShieldResult, ThreatDetector, type ToolCall, type TurnRecord, type ViolationAction, type ViolationRecord };