contextguard 0.1.7 → 0.2.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 (60) hide show
  1. package/LICENSE +23 -17
  2. package/README.md +157 -109
  3. package/dist/agent.d.ts +24 -0
  4. package/dist/agent.js +369 -0
  5. package/dist/cli.d.ts +11 -0
  6. package/dist/cli.js +266 -0
  7. package/dist/config.d.ts +23 -0
  8. package/dist/config.js +56 -0
  9. package/dist/database.d.ts +116 -0
  10. package/dist/database.js +291 -0
  11. package/dist/index.d.ts +16 -0
  12. package/dist/index.js +18 -0
  13. package/dist/init.d.ts +7 -0
  14. package/dist/init.js +173 -0
  15. package/dist/lib/supabase-client.d.ts +27 -0
  16. package/dist/lib/supabase-client.js +97 -0
  17. package/dist/logger.d.ts +36 -0
  18. package/dist/logger.js +145 -0
  19. package/dist/mcp-security-wrapper.d.ts +84 -0
  20. package/dist/mcp-security-wrapper.js +394 -120
  21. package/dist/mcp-traceability-integration.d.ts +118 -0
  22. package/dist/mcp-traceability-integration.js +302 -0
  23. package/dist/policy.d.ts +30 -0
  24. package/dist/policy.js +273 -0
  25. package/dist/premium-features.d.ts +364 -0
  26. package/dist/premium-features.js +950 -0
  27. package/dist/security-logger.d.ts +45 -0
  28. package/dist/security-logger.js +125 -0
  29. package/dist/security-policy.d.ts +55 -0
  30. package/dist/security-policy.js +140 -0
  31. package/dist/semantic-detector.d.ts +21 -0
  32. package/dist/semantic-detector.js +49 -0
  33. package/dist/sse-proxy.d.ts +21 -0
  34. package/dist/sse-proxy.js +276 -0
  35. package/dist/supabase-client.d.ts +27 -0
  36. package/dist/supabase-client.js +89 -0
  37. package/dist/types/database.types.d.ts +220 -0
  38. package/dist/types/database.types.js +8 -0
  39. package/dist/types/mcp.d.ts +27 -0
  40. package/dist/types/mcp.js +15 -0
  41. package/dist/types/types.d.ts +65 -0
  42. package/dist/types/types.js +8 -0
  43. package/dist/types.d.ts +84 -0
  44. package/dist/types.js +8 -0
  45. package/dist/wrapper.d.ts +115 -0
  46. package/dist/wrapper.js +417 -0
  47. package/package.json +35 -10
  48. package/.github/ISSUE_TEMPLATE/bug_report.md +0 -57
  49. package/CONTRIBUTING.md +0 -532
  50. package/SECURITY.md +0 -254
  51. package/assets/demo.mp4 +0 -0
  52. package/eslint.config.mts +0 -23
  53. package/examples/config/config.json +0 -19
  54. package/examples/mcp-server/demo.js +0 -228
  55. package/examples/mcp-server/package-lock.json +0 -978
  56. package/examples/mcp-server/package.json +0 -16
  57. package/examples/mcp-server/pnpm-lock.yaml +0 -745
  58. package/src/mcp-security-wrapper.ts +0 -529
  59. package/test/test-server.ts +0 -295
  60. package/tsconfig.json +0 -16
@@ -0,0 +1,118 @@
1
+ /**
2
+ * Copyright (c) 2025 Amir Mironi
3
+ *
4
+ * MCP Traceability Integration
5
+ * Integrates traceability features with the MCP Security Wrapper
6
+ */
7
+ import { LicenseManager, MCPTraceabilityManager } from "./premium-features";
8
+ /**
9
+ * Enhanced MCP Security Wrapper with Traceability
10
+ */
11
+ export declare class MCPSecurityWrapperWithTraceability {
12
+ private licenseManager;
13
+ private traceabilityManager;
14
+ private contextTracker;
15
+ private sessionId;
16
+ constructor(licenseManager: LicenseManager, sessionId: string);
17
+ /**
18
+ * Wrap MCP tool call with traceability
19
+ */
20
+ executeToolWithTraceability(userId: string, userEmail: string, mcpServerName: string, mcpServerId: string, toolName: string, toolParameters: Record<string, unknown>, toolExecutor: () => Promise<unknown>): Promise<{
21
+ result?: unknown;
22
+ error?: Error;
23
+ traceId: string | null;
24
+ }>;
25
+ /**
26
+ * Record file access in context
27
+ */
28
+ recordFileAccess(path: string, operation: "read" | "write" | "delete" | "list", size?: number): void;
29
+ /**
30
+ * Record environment variable access
31
+ */
32
+ recordEnvVarAccess(varName: string): void;
33
+ /**
34
+ * Record external API call
35
+ */
36
+ recordApiCall(url: string, method: string, statusCode?: number): void;
37
+ /**
38
+ * Get traceability manager for queries
39
+ */
40
+ getTraceabilityManager(): MCPTraceabilityManager;
41
+ }
42
+ /**
43
+ * Example: Integrate with existing MCP server
44
+ */
45
+ export declare function integrateWithMCPServer(): Promise<void>;
46
+ /**
47
+ * Example: Batch processing with traceability
48
+ */
49
+ export declare function batchProcessingWithTraceability(): Promise<void>;
50
+ /**
51
+ * Example: Real-time dashboard data
52
+ */
53
+ export declare function getDashboardData(traceabilityManager: MCPTraceabilityManager): {
54
+ overview: {
55
+ totalTraces: number;
56
+ activeUsers: number;
57
+ activeMCPServers: number;
58
+ threatCount: number;
59
+ };
60
+ recentActivity: Array<{
61
+ timestamp: Date;
62
+ user: string;
63
+ server: string;
64
+ tool: string;
65
+ status: string;
66
+ }>;
67
+ topUsers: Array<{
68
+ userId: string;
69
+ count: number;
70
+ }>;
71
+ topTools: Array<{
72
+ toolName: string;
73
+ count: number;
74
+ }>;
75
+ securityAlerts: Array<{
76
+ timestamp: Date;
77
+ user: string;
78
+ threat: string;
79
+ severity: string;
80
+ }>;
81
+ };
82
+ /**
83
+ * Example: Compliance report generation
84
+ */
85
+ export declare function generateComplianceReport(traceabilityManager: MCPTraceabilityManager, startDate: Date, endDate: Date): {
86
+ reportId: string;
87
+ period: {
88
+ start: Date;
89
+ end: Date;
90
+ };
91
+ summary: {
92
+ totalOperations: number;
93
+ uniqueUsers: number;
94
+ securityIncidents: number;
95
+ complianceScore: number;
96
+ };
97
+ userActivity: Array<{
98
+ userId: string;
99
+ operations: number;
100
+ mcpServers: string[];
101
+ securityIncidents: number;
102
+ }>;
103
+ securityIncidents: Array<{
104
+ timestamp: Date;
105
+ userId: string;
106
+ description: string;
107
+ severity: string;
108
+ }>;
109
+ recommendations: string[];
110
+ };
111
+ declare const _default: {
112
+ MCPSecurityWrapperWithTraceability: typeof MCPSecurityWrapperWithTraceability;
113
+ integrateWithMCPServer: typeof integrateWithMCPServer;
114
+ batchProcessingWithTraceability: typeof batchProcessingWithTraceability;
115
+ getDashboardData: typeof getDashboardData;
116
+ generateComplianceReport: typeof generateComplianceReport;
117
+ };
118
+ export default _default;
@@ -0,0 +1,302 @@
1
+ "use strict";
2
+ /**
3
+ * Copyright (c) 2025 Amir Mironi
4
+ *
5
+ * MCP Traceability Integration
6
+ * Integrates traceability features with the MCP Security Wrapper
7
+ */
8
+ Object.defineProperty(exports, "__esModule", { value: true });
9
+ exports.MCPSecurityWrapperWithTraceability = void 0;
10
+ exports.integrateWithMCPServer = integrateWithMCPServer;
11
+ exports.batchProcessingWithTraceability = batchProcessingWithTraceability;
12
+ exports.getDashboardData = getDashboardData;
13
+ exports.generateComplianceReport = generateComplianceReport;
14
+ const premium_features_1 = require("./premium-features");
15
+ /**
16
+ * Enhanced MCP Security Wrapper with Traceability
17
+ */
18
+ class MCPSecurityWrapperWithTraceability {
19
+ constructor(licenseManager, sessionId) {
20
+ this.licenseManager = licenseManager;
21
+ this.traceabilityManager = new premium_features_1.MCPTraceabilityManager(licenseManager);
22
+ this.contextTracker = new premium_features_1.ContextTracker(licenseManager);
23
+ this.sessionId = sessionId;
24
+ }
25
+ /**
26
+ * Wrap MCP tool call with traceability
27
+ */
28
+ async executeToolWithTraceability(userId, userEmail, mcpServerName, mcpServerId, toolName, toolParameters, toolExecutor) {
29
+ // Start context tracking
30
+ this.contextTracker.startTracking(this.sessionId);
31
+ const startTime = Date.now();
32
+ let result;
33
+ let error;
34
+ let status = "success";
35
+ let securityViolations = [];
36
+ let threatDetected = false;
37
+ try {
38
+ // Execute the tool
39
+ result = await toolExecutor();
40
+ }
41
+ catch (err) {
42
+ error = err instanceof Error ? err : new Error(String(err));
43
+ status = "failure";
44
+ }
45
+ // Get context snapshot
46
+ const contextSnapshot = this.contextTracker.stopTracking(this.sessionId);
47
+ // Analyze context for security risks
48
+ if (contextSnapshot) {
49
+ const securityRisks = this.contextTracker.analyzeContextSecurity(contextSnapshot);
50
+ if (securityRisks.length > 0) {
51
+ threatDetected = true;
52
+ securityViolations = securityRisks.map((risk) => `[${risk.severity}] ${risk.risk}: ${risk.details}`);
53
+ // Block if critical risks detected
54
+ const hasCriticalRisk = securityRisks.some((r) => r.severity === "CRITICAL");
55
+ if (hasCriticalRisk) {
56
+ status = "blocked";
57
+ }
58
+ }
59
+ }
60
+ // Record trace
61
+ const traceId = this.traceabilityManager.recordTrace({
62
+ userId,
63
+ userEmail,
64
+ sessionId: this.sessionId,
65
+ mcpServerName,
66
+ mcpServerId,
67
+ toolName,
68
+ toolParameters,
69
+ contextUsed: contextSnapshot || {
70
+ filesAccessed: [],
71
+ envVarsAccessed: [],
72
+ externalApisCalled: [],
73
+ },
74
+ executionTimeMs: Date.now() - startTime,
75
+ status,
76
+ errorMessage: error?.message,
77
+ securityLevel: threatDetected ? "restricted" : "internal",
78
+ complianceTags: ["SOC2"],
79
+ threatDetected,
80
+ securityViolations,
81
+ });
82
+ return {
83
+ result: status !== "blocked" ? result : undefined,
84
+ error: status === "blocked" ? new Error("Request blocked due to security violations") : error,
85
+ traceId,
86
+ };
87
+ }
88
+ /**
89
+ * Record file access in context
90
+ */
91
+ recordFileAccess(path, operation, size) {
92
+ this.contextTracker.recordFileAccess(this.sessionId, path, operation, size);
93
+ }
94
+ /**
95
+ * Record environment variable access
96
+ */
97
+ recordEnvVarAccess(varName) {
98
+ this.contextTracker.recordEnvVarAccess(this.sessionId, varName);
99
+ }
100
+ /**
101
+ * Record external API call
102
+ */
103
+ recordApiCall(url, method, statusCode) {
104
+ this.contextTracker.recordApiCall(this.sessionId, url, method, statusCode);
105
+ }
106
+ /**
107
+ * Get traceability manager for queries
108
+ */
109
+ getTraceabilityManager() {
110
+ return this.traceabilityManager;
111
+ }
112
+ }
113
+ exports.MCPSecurityWrapperWithTraceability = MCPSecurityWrapperWithTraceability;
114
+ /**
115
+ * Example: Integrate with existing MCP server
116
+ */
117
+ async function integrateWithMCPServer() {
118
+ const licenseManager = new premium_features_1.LicenseManager(".contextguard-license");
119
+ const sessionId = `session-${Date.now()}`;
120
+ const wrapper = new MCPSecurityWrapperWithTraceability(licenseManager, sessionId);
121
+ // Example tool execution
122
+ const { result, error, traceId } = await wrapper.executeToolWithTraceability("user-123", "user@example.com", "filesystem-mcp", "fs-001", "read_file", { path: "/home/user/config.json" }, async () => {
123
+ // Record context during execution
124
+ wrapper.recordFileAccess("/home/user/config.json", "read", 1024);
125
+ wrapper.recordEnvVarAccess("HOME");
126
+ // Simulate file read
127
+ return { content: "file content here" };
128
+ });
129
+ if (error) {
130
+ console.error(`Tool execution failed: ${error.message}`);
131
+ }
132
+ else {
133
+ console.log(`Tool executed successfully. Trace ID: ${traceId}`);
134
+ console.log(`Result:`, result);
135
+ }
136
+ // Query traces
137
+ const traces = wrapper.getTraceabilityManager().queryTraces({
138
+ userId: "user-123",
139
+ limit: 10,
140
+ });
141
+ console.log(`\nRecent traces: ${traces.length}`);
142
+ }
143
+ /**
144
+ * Example: Batch processing with traceability
145
+ */
146
+ async function batchProcessingWithTraceability() {
147
+ const licenseManager = new premium_features_1.LicenseManager(".contextguard-license");
148
+ const traceabilityManager = new premium_features_1.MCPTraceabilityManager(licenseManager);
149
+ const tasks = [
150
+ { userId: "user-1", tool: "read_file", params: { path: "/file1.txt" } },
151
+ { userId: "user-2", tool: "write_file", params: { path: "/file2.txt" } },
152
+ { userId: "user-3", tool: "list_dir", params: { path: "/home" } },
153
+ ];
154
+ console.log("Processing batch with traceability...\n");
155
+ for (const task of tasks) {
156
+ const sessionId = `session-${Date.now()}-${task.userId}`;
157
+ const contextTracker = new premium_features_1.ContextTracker(licenseManager);
158
+ contextTracker.startTracking(sessionId);
159
+ const startTime = Date.now();
160
+ // Simulate task execution
161
+ await new Promise((resolve) => setTimeout(resolve, Math.random() * 100));
162
+ const contextSnapshot = contextTracker.stopTracking(sessionId);
163
+ traceabilityManager.recordTrace({
164
+ userId: task.userId,
165
+ sessionId,
166
+ mcpServerName: "filesystem-mcp",
167
+ mcpServerId: "fs-001",
168
+ toolName: task.tool,
169
+ toolParameters: task.params,
170
+ contextUsed: contextSnapshot || {
171
+ filesAccessed: [],
172
+ envVarsAccessed: [],
173
+ externalApisCalled: [],
174
+ },
175
+ executionTimeMs: Date.now() - startTime,
176
+ status: "success",
177
+ securityLevel: "internal",
178
+ complianceTags: ["SOC2"],
179
+ threatDetected: false,
180
+ securityViolations: [],
181
+ });
182
+ console.log(`āœ… Processed: ${task.userId} - ${task.tool}`);
183
+ }
184
+ // Get statistics
185
+ const stats = traceabilityManager.getUsageStatistics();
186
+ console.log(`\nšŸ“Š Batch Statistics:`);
187
+ console.log(` Total Traces: ${stats.totalTraces}`);
188
+ console.log(` Unique Users: ${stats.uniqueUsers}`);
189
+ console.log(` Unique Tools: ${stats.uniqueTools}`);
190
+ }
191
+ /**
192
+ * Example: Real-time dashboard data
193
+ */
194
+ function getDashboardData(traceabilityManager) {
195
+ const stats = traceabilityManager.getUsageStatistics();
196
+ // Recent activity
197
+ const recentTraces = traceabilityManager.queryTraces({
198
+ limit: 20,
199
+ sortBy: "timestamp",
200
+ sortOrder: "desc",
201
+ });
202
+ const recentActivity = recentTraces.map((trace) => ({
203
+ timestamp: trace.timestamp,
204
+ user: trace.userId,
205
+ server: trace.mcpServerName,
206
+ tool: trace.toolName,
207
+ status: trace.status,
208
+ }));
209
+ // Top users
210
+ const topUsers = Object.entries(stats.byUser)
211
+ .map(([userId, data]) => ({ userId, count: data.count }))
212
+ .sort((a, b) => b.count - a.count)
213
+ .slice(0, 10);
214
+ // Top tools
215
+ const topTools = Object.entries(stats.byTool)
216
+ .map(([toolName, data]) => ({ toolName, count: data.count }))
217
+ .sort((a, b) => b.count - a.count)
218
+ .slice(0, 10);
219
+ // Security alerts
220
+ const threatTraces = traceabilityManager.queryTraces({
221
+ threatDetected: true,
222
+ limit: 50,
223
+ });
224
+ const securityAlerts = threatTraces.map((trace) => ({
225
+ timestamp: trace.timestamp,
226
+ user: trace.userId,
227
+ threat: trace.securityViolations.join(", "),
228
+ severity: "HIGH",
229
+ }));
230
+ return {
231
+ overview: {
232
+ totalTraces: stats.totalTraces,
233
+ activeUsers: stats.uniqueUsers,
234
+ activeMCPServers: stats.uniqueMCPServers,
235
+ threatCount: stats.securityEvents.totalThreats,
236
+ },
237
+ recentActivity,
238
+ topUsers,
239
+ topTools,
240
+ securityAlerts,
241
+ };
242
+ }
243
+ /**
244
+ * Example: Compliance report generation
245
+ */
246
+ function generateComplianceReport(traceabilityManager, startDate, endDate) {
247
+ const traces = traceabilityManager.queryTraces({
248
+ startDate,
249
+ endDate,
250
+ limit: 10000,
251
+ });
252
+ const stats = traceabilityManager.getUsageStatistics({ startDate, endDate });
253
+ // Calculate compliance score (0-100)
254
+ const totalOperations = traces.length;
255
+ const securityIncidentCount = traces.filter((t) => t.threatDetected).length;
256
+ const complianceScore = Math.max(0, 100 - (securityIncidentCount / totalOperations) * 100);
257
+ // User activity
258
+ const userActivity = Object.entries(stats.byUser).map(([userId, data]) => ({
259
+ userId,
260
+ operations: data.count,
261
+ mcpServers: data.mcpServersUsed,
262
+ securityIncidents: traces.filter((t) => t.userId === userId && t.threatDetected).length,
263
+ }));
264
+ // Security incidents
265
+ const securityIncidentsList = traces
266
+ .filter((t) => t.threatDetected)
267
+ .map((t) => ({
268
+ timestamp: t.timestamp,
269
+ userId: t.userId,
270
+ description: t.securityViolations.join(", "),
271
+ severity: "HIGH",
272
+ }));
273
+ // Recommendations
274
+ const recommendations = [];
275
+ if (securityIncidentsList.length > 0) {
276
+ recommendations.push(`Review and address ${securityIncidentsList.length} security incidents`);
277
+ }
278
+ if (complianceScore < 95) {
279
+ recommendations.push("Improve security controls to achieve 95%+ compliance score");
280
+ }
281
+ return {
282
+ reportId: `report-${Date.now()}`,
283
+ period: { start: startDate, end: endDate },
284
+ summary: {
285
+ totalOperations,
286
+ uniqueUsers: stats.uniqueUsers,
287
+ securityIncidents: securityIncidentCount,
288
+ complianceScore,
289
+ },
290
+ userActivity,
291
+ securityIncidents: securityIncidentsList,
292
+ recommendations,
293
+ };
294
+ }
295
+ // Export all functions
296
+ exports.default = {
297
+ MCPSecurityWrapperWithTraceability,
298
+ integrateWithMCPServer,
299
+ batchProcessingWithTraceability,
300
+ getDashboardData,
301
+ generateComplianceReport,
302
+ };
@@ -0,0 +1,30 @@
1
+ /**
2
+ * Copyright (c) 2026 Amir Mironi
3
+ *
4
+ * This source code is licensed under the MIT license found in the
5
+ * LICENSE file in the root directory of this source tree.
6
+ */
7
+ import { AgentPolicyRow } from "./types/database.types";
8
+ /**
9
+ * Policy checker interface
10
+ */
11
+ export interface PolicyChecker {
12
+ checkPromptInjection: (text: string) => string[];
13
+ checkSensitiveData: (text: string) => string[];
14
+ checkFileAccess: (filePath: string) => string[];
15
+ checkRateLimit: (timestamps: number[]) => boolean;
16
+ checkBlockedPatterns: (text: string) => string[];
17
+ checkToolAccess: (toolName: string) => string[];
18
+ checkSQLInjection: (text: string) => string[];
19
+ checkXSS: (text: string) => string[];
20
+ checkCustomRules: (text: string) => string[];
21
+ isBlockingMode: () => boolean;
22
+ getConfig: () => Required<AgentPolicyRow>;
23
+ }
24
+ /**
25
+ * Create a policy checker with the given configuration
26
+ * @param config - Policy configuration
27
+ * @returns Policy checker functions
28
+ */
29
+ export declare const createPolicyChecker: (config: Required<AgentPolicyRow>) => PolicyChecker;
30
+ export declare const DEFAULT_POLICY: Required<AgentPolicyRow>;