@defai.digital/mcp-runtime 13.0.3

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 (46) hide show
  1. package/LICENSE +214 -0
  2. package/dist/cache/index.d.ts +2 -0
  3. package/dist/cache/index.d.ts.map +1 -0
  4. package/dist/cache/index.js +2 -0
  5. package/dist/cache/index.js.map +1 -0
  6. package/dist/cache/lru-cache.d.ts +97 -0
  7. package/dist/cache/lru-cache.d.ts.map +1 -0
  8. package/dist/cache/lru-cache.js +295 -0
  9. package/dist/cache/lru-cache.js.map +1 -0
  10. package/dist/guard/index.d.ts +2 -0
  11. package/dist/guard/index.d.ts.map +1 -0
  12. package/dist/guard/index.js +6 -0
  13. package/dist/guard/index.js.map +1 -0
  14. package/dist/guard/runtime-guard.d.ts +98 -0
  15. package/dist/guard/runtime-guard.d.ts.map +1 -0
  16. package/dist/guard/runtime-guard.js +204 -0
  17. package/dist/guard/runtime-guard.js.map +1 -0
  18. package/dist/index.d.ts +6 -0
  19. package/dist/index.d.ts.map +1 -0
  20. package/dist/index.js +19 -0
  21. package/dist/index.js.map +1 -0
  22. package/dist/response/helpers.d.ts +118 -0
  23. package/dist/response/helpers.d.ts.map +1 -0
  24. package/dist/response/helpers.js +235 -0
  25. package/dist/response/helpers.js.map +1 -0
  26. package/dist/response/index.d.ts +2 -0
  27. package/dist/response/index.d.ts.map +1 -0
  28. package/dist/response/index.js +6 -0
  29. package/dist/response/index.js.map +1 -0
  30. package/dist/timeout/index.d.ts +2 -0
  31. package/dist/timeout/index.d.ts.map +1 -0
  32. package/dist/timeout/index.js +2 -0
  33. package/dist/timeout/index.js.map +1 -0
  34. package/dist/timeout/wrapper.d.ts +52 -0
  35. package/dist/timeout/wrapper.d.ts.map +1 -0
  36. package/dist/timeout/wrapper.js +133 -0
  37. package/dist/timeout/wrapper.js.map +1 -0
  38. package/dist/validation/index.d.ts +2 -0
  39. package/dist/validation/index.d.ts.map +1 -0
  40. package/dist/validation/index.js +2 -0
  41. package/dist/validation/index.js.map +1 -0
  42. package/dist/validation/request-validator.d.ts +28 -0
  43. package/dist/validation/request-validator.d.ts.map +1 -0
  44. package/dist/validation/request-validator.js +151 -0
  45. package/dist/validation/request-validator.js.map +1 -0
  46. package/package.json +41 -0
@@ -0,0 +1,98 @@
1
+ import type { MCPCacheStats, MCPRequestLimits } from '@defai.digital/contracts';
2
+ export type GuardStatus = 'PASS' | 'WARN' | 'FAIL';
3
+ export interface GuardCheckResult {
4
+ status: GuardStatus;
5
+ gate: string;
6
+ message: string;
7
+ details?: Record<string, unknown>;
8
+ /** Suggested action when check fails */
9
+ suggestion?: string;
10
+ /** Audit data for logging */
11
+ audit?: Record<string, unknown>;
12
+ }
13
+ export interface RuntimeGuardResult {
14
+ /** Overall status (FAIL if any gate fails) */
15
+ status: GuardStatus;
16
+ /** Individual gate results */
17
+ gates: GuardCheckResult[];
18
+ /** Human-readable summary */
19
+ summary: string;
20
+ /** Whether the request should proceed */
21
+ allowed: boolean;
22
+ /** Timestamp of check */
23
+ timestamp: string;
24
+ }
25
+ export interface RuntimeGuardConfig {
26
+ /** Enable memory pressure checks */
27
+ checkMemoryPressure: boolean;
28
+ /** Enable request validation */
29
+ checkRequestLimits: boolean;
30
+ /** Block on critical memory pressure */
31
+ blockOnCriticalPressure: boolean;
32
+ /** Block on validation failures */
33
+ blockOnValidationFailure: boolean;
34
+ /** Custom request limits */
35
+ requestLimits?: MCPRequestLimits;
36
+ }
37
+ export declare const DEFAULT_GUARD_CONFIG: RuntimeGuardConfig;
38
+ export interface RuntimeGuardContext {
39
+ /** Tool being called */
40
+ toolName: string;
41
+ /** Tool arguments */
42
+ args: unknown;
43
+ /** Current cache stats (optional) */
44
+ cacheStats?: MCPCacheStats | undefined;
45
+ /** Request size in bytes (optional) */
46
+ requestSizeBytes?: number | undefined;
47
+ /** Request ID for tracing */
48
+ requestId?: string | undefined;
49
+ }
50
+ /**
51
+ * Runtime guard for MCP operations.
52
+ *
53
+ * Enforces runtime governance policies:
54
+ * - Memory pressure checks
55
+ * - Request size and array limits
56
+ * - Timeout tracking (via audit)
57
+ *
58
+ * Invariants:
59
+ * - INV-MCP-GUARD-001: Critical pressure blocks operations
60
+ * - INV-MCP-GUARD-002: Invalid requests rejected before processing
61
+ * - INV-MCP-GUARD-003: All checks logged for audit
62
+ */
63
+ export declare class RuntimeGuard {
64
+ private readonly config;
65
+ private readonly limits;
66
+ constructor(config?: Partial<RuntimeGuardConfig>);
67
+ /**
68
+ * Run all guard checks for a request.
69
+ */
70
+ check(context: RuntimeGuardContext): Promise<RuntimeGuardResult>;
71
+ /**
72
+ * Check memory pressure.
73
+ * INV-MCP-GUARD-001: Critical pressure blocks operations.
74
+ */
75
+ private checkMemoryPressure;
76
+ /**
77
+ * Check request limits.
78
+ * INV-MCP-GUARD-002: Invalid requests rejected before processing.
79
+ */
80
+ private checkRequestLimits;
81
+ /**
82
+ * Determine if request should be allowed based on results.
83
+ */
84
+ private shouldAllow;
85
+ /**
86
+ * Generate human-readable summary.
87
+ */
88
+ private generateSummary;
89
+ }
90
+ /**
91
+ * Create a runtime guard instance.
92
+ */
93
+ export declare function createRuntimeGuard(config?: Partial<RuntimeGuardConfig>): RuntimeGuard;
94
+ /**
95
+ * Quick check helper for common use case.
96
+ */
97
+ export declare function quickGuardCheck(toolName: string, args: unknown, cacheStats?: MCPCacheStats): Promise<RuntimeGuardResult>;
98
+ //# sourceMappingURL=runtime-guard.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"runtime-guard.d.ts","sourceRoot":"","sources":["../../src/guard/runtime-guard.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,aAAa,EACb,gBAAgB,EAEjB,MAAM,0BAA0B,CAAC;AAOlC,MAAM,MAAM,WAAW,GAAG,MAAM,GAAG,MAAM,GAAG,MAAM,CAAC;AAEnD,MAAM,WAAW,gBAAgB;IAC/B,MAAM,EAAE,WAAW,CAAC;IACpB,IAAI,EAAE,MAAM,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C5C,OAAO,CAAC,QAAQ,CAAC,MAAM,CAA+B;gBAE1C,MAAM,GAAE,OAAO,CAAC,kBAAkB,CAAM;IAKpD;;OAEG;IACG,KAAK,CAAC,OAAO,EAAE,mBAAmB,GAAG,OAAO,CAAC,kBAAkB,CAAC;IAuDtE;;;OAGG;IACH,OAAO,CAAC,mBAAmB;IA8C3B;;;OAGG;IACH,OAAO,CAAC,kBAAkB;IA8B1B;;OAEG;IACH,OAAO,CAAC,WAAW;IAsBnB;;OAEG;IACH,OAAO,CAAC,eAAe;CAexB;AAED;;GAEG;AACH,wBAAgB,kBAAkB,CAChC,MAAM,CAAC,EAAE,OAAO,CAAC,kBAAkB,CAAC,GACnC,YAAY,CAEd;AAED;;GAEG;AACH,wBAAsB,eAAe,CACnC,QAAQ,EAAE,MAAM,EAChB,IAAI,EAAE,OAAO,EACb,UAAU,CAAC,EAAE,aAAa,GACzB,OAAO,CAAC,kBAAkB,CAAC,CAG7B"}
@@ -0,0 +1,204 @@
1
+ import { validateRequest } from '../validation/request-validator.js';
2
+ export const DEFAULT_GUARD_CONFIG = {
3
+ checkMemoryPressure: true,
4
+ checkRequestLimits: true,
5
+ blockOnCriticalPressure: true,
6
+ blockOnValidationFailure: true,
7
+ };
8
+ // ============================================================================
9
+ // Guard Implementation
10
+ // ============================================================================
11
+ /**
12
+ * Runtime guard for MCP operations.
13
+ *
14
+ * Enforces runtime governance policies:
15
+ * - Memory pressure checks
16
+ * - Request size and array limits
17
+ * - Timeout tracking (via audit)
18
+ *
19
+ * Invariants:
20
+ * - INV-MCP-GUARD-001: Critical pressure blocks operations
21
+ * - INV-MCP-GUARD-002: Invalid requests rejected before processing
22
+ * - INV-MCP-GUARD-003: All checks logged for audit
23
+ */
24
+ export class RuntimeGuard {
25
+ config;
26
+ limits;
27
+ constructor(config = {}) {
28
+ this.config = { ...DEFAULT_GUARD_CONFIG, ...config };
29
+ this.limits = config.requestLimits;
30
+ }
31
+ /**
32
+ * Run all guard checks for a request.
33
+ */
34
+ async check(context) {
35
+ const gates = [];
36
+ let hasFailure = false;
37
+ let hasWarning = false;
38
+ // Memory pressure check
39
+ if (this.config.checkMemoryPressure && context.cacheStats) {
40
+ const pressureResult = this.checkMemoryPressure(context.cacheStats);
41
+ gates.push(pressureResult);
42
+ if (pressureResult.status === 'FAIL') {
43
+ hasFailure = true;
44
+ }
45
+ else if (pressureResult.status === 'WARN') {
46
+ hasWarning = true;
47
+ }
48
+ }
49
+ // Request validation check
50
+ if (this.config.checkRequestLimits) {
51
+ const validationResult = this.checkRequestLimits(context.toolName, context.args);
52
+ gates.push(validationResult);
53
+ if (validationResult.status === 'FAIL') {
54
+ hasFailure = true;
55
+ }
56
+ else if (validationResult.status === 'WARN') {
57
+ hasWarning = true;
58
+ }
59
+ }
60
+ // Determine overall status
61
+ let status = 'PASS';
62
+ if (hasFailure) {
63
+ status = 'FAIL';
64
+ }
65
+ else if (hasWarning) {
66
+ status = 'WARN';
67
+ }
68
+ // Determine if request should proceed
69
+ const allowed = this.shouldAllow(status, gates);
70
+ // Generate summary
71
+ const summary = this.generateSummary(status, gates);
72
+ return {
73
+ status,
74
+ gates,
75
+ summary,
76
+ allowed,
77
+ timestamp: new Date().toISOString(),
78
+ };
79
+ }
80
+ /**
81
+ * Check memory pressure.
82
+ * INV-MCP-GUARD-001: Critical pressure blocks operations.
83
+ */
84
+ checkMemoryPressure(stats) {
85
+ const { pressureLevel, currentSizeBytes, maxSizeBytes, hitRate } = stats;
86
+ if (pressureLevel === 'critical') {
87
+ return {
88
+ status: this.config.blockOnCriticalPressure ? 'FAIL' : 'WARN',
89
+ gate: 'memory_pressure',
90
+ message: `Memory pressure is critical (${Math.round((currentSizeBytes / maxSizeBytes) * 100)}% used)`,
91
+ details: {
92
+ pressureLevel,
93
+ usagePercent: (currentSizeBytes / maxSizeBytes) * 100,
94
+ currentSizeBytes,
95
+ maxSizeBytes,
96
+ hitRate,
97
+ },
98
+ suggestion: 'Wait for cache eviction or increase maxSizeBytes',
99
+ };
100
+ }
101
+ if (pressureLevel === 'high') {
102
+ return {
103
+ status: 'WARN',
104
+ gate: 'memory_pressure',
105
+ message: `Memory pressure is high (${Math.round((currentSizeBytes / maxSizeBytes) * 100)}% used)`,
106
+ details: {
107
+ pressureLevel,
108
+ usagePercent: (currentSizeBytes / maxSizeBytes) * 100,
109
+ currentSizeBytes,
110
+ maxSizeBytes,
111
+ hitRate,
112
+ },
113
+ suggestion: 'Consider reducing cache usage or increasing limits',
114
+ };
115
+ }
116
+ return {
117
+ status: 'PASS',
118
+ gate: 'memory_pressure',
119
+ message: `Memory pressure is ${pressureLevel}`,
120
+ details: {
121
+ pressureLevel,
122
+ usagePercent: (currentSizeBytes / maxSizeBytes) * 100,
123
+ },
124
+ };
125
+ }
126
+ /**
127
+ * Check request limits.
128
+ * INV-MCP-GUARD-002: Invalid requests rejected before processing.
129
+ */
130
+ checkRequestLimits(toolName, args) {
131
+ const result = validateRequest(toolName, args, this.limits);
132
+ if (!result.valid) {
133
+ const errors = result.errors;
134
+ const errorMessages = errors.map((e) => e.message).join('; ');
135
+ return {
136
+ status: this.config.blockOnValidationFailure ? 'FAIL' : 'WARN',
137
+ gate: 'request_limits',
138
+ message: `Request validation failed: ${errorMessages}`,
139
+ details: {
140
+ errors,
141
+ toolName,
142
+ },
143
+ suggestion: 'Reduce array sizes or split into multiple requests',
144
+ };
145
+ }
146
+ return {
147
+ status: 'PASS',
148
+ gate: 'request_limits',
149
+ message: 'Request validation passed',
150
+ details: { toolName },
151
+ };
152
+ }
153
+ /**
154
+ * Determine if request should be allowed based on results.
155
+ */
156
+ shouldAllow(status, gates) {
157
+ if (status === 'PASS' || status === 'WARN') {
158
+ return true;
159
+ }
160
+ // Check if any blocking failures exist
161
+ for (const gate of gates) {
162
+ if (gate.status === 'FAIL') {
163
+ // Memory pressure failure
164
+ if (gate.gate === 'memory_pressure' && this.config.blockOnCriticalPressure) {
165
+ return false;
166
+ }
167
+ // Validation failure
168
+ if (gate.gate === 'request_limits' && this.config.blockOnValidationFailure) {
169
+ return false;
170
+ }
171
+ }
172
+ }
173
+ return true;
174
+ }
175
+ /**
176
+ * Generate human-readable summary.
177
+ */
178
+ generateSummary(status, gates) {
179
+ const passCount = gates.filter((g) => g.status === 'PASS').length;
180
+ const warnCount = gates.filter((g) => g.status === 'WARN').length;
181
+ const failCount = gates.filter((g) => g.status === 'FAIL').length;
182
+ if (status === 'PASS') {
183
+ return `All ${gates.length} checks passed`;
184
+ }
185
+ if (status === 'WARN') {
186
+ return `${passCount} passed, ${warnCount} warnings`;
187
+ }
188
+ return `${failCount} failed, ${warnCount} warnings, ${passCount} passed`;
189
+ }
190
+ }
191
+ /**
192
+ * Create a runtime guard instance.
193
+ */
194
+ export function createRuntimeGuard(config) {
195
+ return new RuntimeGuard(config);
196
+ }
197
+ /**
198
+ * Quick check helper for common use case.
199
+ */
200
+ export async function quickGuardCheck(toolName, args, cacheStats) {
201
+ const guard = createRuntimeGuard();
202
+ return guard.check({ toolName, args, cacheStats });
203
+ }
204
+ //# sourceMappingURL=runtime-guard.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"runtime-guard.js","sourceRoot":"","sources":["../../src/guard/runtime-guard.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,eAAe,EAAE,MAAM,oCAAoC,CAAC;AAiDrE,MAAM,CAAC,MAAM,oBAAoB,GAAuB;IACtD,mBAAmB,EAAE,IAAI;IACzB,kBAAkB,EAAE,IAAI;IACxB,uBAAuB,EAAE,IAAI;IAC7B,wBAAwB,EAAE,IAAI;CAC/B,CAAC;AAmBF,+EAA+E;AAC/E,uBAAuB;AACvB,+EAA+E;AAE/E;;;;;;;;;;;;GAYG;AACH,MAAM,OAAO,YAAY;IACN,MAAM,CAAqB;IAC3B,MAAM,CAA+B;IAEtD,YAAY,SAAsC,EAAE;QAClD,IAAI,CAAC,MAAM,GAAG,EAAE,GAAG,oBAAoB,EAAE,GAAG,MAAM,EAAE,CAAC;QACrD,IAAI,CAAC,MAAM,GAA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G,SAAS,YAAY,SAAS,cAAc,SAAS,SAAS,CAAC;IAC3E,CAAC;CACF;AAED;;GAEG;AACH,MAAM,UAAU,kBAAkB,CAChC,MAAoC;IAEpC,OAAO,IAAI,YAAY,CAAC,MAAM,CAAC,CAAC;AAClC,CAAC;AAED;;GAEG;AACH,MAAM,CAAC,KAAK,UAAU,eAAe,CACnC,QAAgB,EAChB,IAAa,EACb,UAA0B;IAE1B,MAAM,KAAK,GAAG,kBAAkB,EAAE,CAAC;IACnC,OAAO,KAAK,CAAC,KAAK,CAAC,EAAE,QAAQ,EAAE,IAAI,EAAE,UAAU,EAAE,CAAC,CAAC;AACrD,CAAC"}
@@ -0,0 +1,6 @@
1
+ export { LRUCache, createLRUCache } from './cache/index.js';
2
+ export { DEFAULT_TIMEOUT_CONFIG, TimeoutError, withTimeout, withToolTimeout, createTimeoutWrapper, getToolCategory, isTimeoutResult, isSuccessResult, unwrapResult, } from './timeout/index.js';
3
+ export { type MCPToolResult, type SuccessResponseData, type ErrorResponseData, type ResponseData, createSuccessResponse, createErrorResponse, createListResponse, createNotFoundResponse, createValidationErrorResponse, createTimeoutResponse, createMemoryPressureResponse, createInternalErrorResponse, truncateString, truncateResponse, } from './response/index.js';
4
+ export { validateRequest, createValidationMiddleware, isValidRequest, formatValidationErrors, } from './validation/index.js';
5
+ export { type GuardStatus, type GuardCheckResult, type RuntimeGuardResult, type RuntimeGuardConfig, type RuntimeGuardContext, DEFAULT_GUARD_CONFIG, RuntimeGuard, createRuntimeGuard, quickGuardCheck, } from './guard/index.js';
6
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,QAAQ,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAG5D,OAAO,EACL,sBAAsB,EACtB,YAAY,EACZ,WAAW,EACX,eAAe,EACf,oBAAoB,EACpB,eAAe,EACf,eAAe,EACf,eAAe,EACf,YAAY,GACb,MAAM,oBAAoB,CAAC;AAG5B,OAAO,EAEL,KAAK,aAAa,EAClB,KAAK,mBAAmB,EACxB,KAAK,iBAAiB,EACtB,KAAK,YAAY,EAGjB,qBAAqB,EACrB,mBAAmB,EACnB,kBAAkB,EAClB,sBAAsB,EACtB,6BAA6B,EAC7B,qBAAqB,EACrB,4BAA4B,EAC5B,2BAA2B,EAG3B,cAAc,EACd,gBAAgB,GACjB,MAAM,qBAAqB,CAAC;AAG7B,OAAO,EACL,eAAe,EACf,0BAA0B,EAC1B,cAAc,EACd,sBAAsB,GACvB,MAAM,uBAAuB,CAAC;AAG/B,OAAO,EAEL,KAAK,WAAW,EAChB,KAAK,gBAAgB,EACrB,KAAK,kBAAkB,EACvB,KAAK,kBAAkB,EACvB,KAAK,mBAAmB,EAGxB,oBAAoB,EAGpB,YAAY,EACZ,kBAAkB,EAClB,eAAe,GAChB,MAAM,kBAAkB,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,19 @@
1
+ // Cache module
2
+ export { LRUCache, createLRUCache } from './cache/index.js';
3
+ // Timeout module
4
+ export { DEFAULT_TIMEOUT_CONFIG, TimeoutError, withTimeout, withToolTimeout, createTimeoutWrapper, getToolCategory, isTimeoutResult, isSuccessResult, unwrapResult, } from './timeout/index.js';
5
+ // Response module
6
+ export {
7
+ // Response helpers
8
+ createSuccessResponse, createErrorResponse, createListResponse, createNotFoundResponse, createValidationErrorResponse, createTimeoutResponse, createMemoryPressureResponse, createInternalErrorResponse,
9
+ // Truncation helpers
10
+ truncateString, truncateResponse, } from './response/index.js';
11
+ // Validation module
12
+ export { validateRequest, createValidationMiddleware, isValidRequest, formatValidationErrors, } from './validation/index.js';
13
+ // Guard module
14
+ export {
15
+ // Constants
16
+ DEFAULT_GUARD_CONFIG,
17
+ // Class and helpers
18
+ RuntimeGuard, createRuntimeGuard, quickGuardCheck, } from './guard/index.js';
19
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,eAAe;AACf,OAAO,EAAE,QAAQ,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAE5D,iBAAiB;AACjB,OAAO,EACL,sBAAsB,EACtB,YAAY,EACZ,WAAW,EACX,eAAe,EACf,oBAAoB,EACpB,eAAe,EACf,eAAe,EACf,eAAe,EACf,YAAY,GACb,MAAM,oBAAoB,CAAC;AAE5B,kBAAkB;AAClB,OAAO;AAOL,mBAAmB;AACnB,qBAAqB,EACrB,mBAAmB,EACnB,kBAAkB,EAClB,sBAAsB,EACtB,6BAA6B,EAC7B,qBAAqB,EACrB,4BAA4B,EAC5B,2BAA2B;AAE3B,qBAAqB;AACrB,cAAc,EACd,gBAAgB,GACjB,MAAM,qBAAqB,CAAC;AAE7B,oBAAoB;AACpB,OAAO,EACL,eAAe,EACf,0BAA0B,EAC1B,cAAc,EACd,sBAAsB,GACvB,MAAM,uBAAuB,CAAC;AAE/B,eAAe;AACf,OAAO;AAQL,YAAY;AACZ,oBAAoB;AAEpB,oBAAoB;AACpB,YAAY,EACZ,kBAAkB,EAClB,eAAe,GAChB,MAAM,kBAAkB,CAAC"}
@@ -0,0 +1,118 @@
1
+ import type { MCPErrorCode, MCPStructuredError, MCPResponseMetadata, MCPResponseLimits } from '@defai.digital/contracts';
2
+ export interface MCPToolResult {
3
+ content: {
4
+ type: 'text';
5
+ text: string;
6
+ }[];
7
+ isError?: boolean;
8
+ }
9
+ export interface SuccessResponseData<T> {
10
+ success: true;
11
+ data: T;
12
+ metadata?: MCPResponseMetadata;
13
+ }
14
+ export interface ErrorResponseData {
15
+ success: false;
16
+ error: MCPStructuredError;
17
+ metadata?: MCPResponseMetadata;
18
+ }
19
+ export type ResponseData<T> = SuccessResponseData<T> | ErrorResponseData;
20
+ /**
21
+ * Create a success response.
22
+ *
23
+ * INV-MCP-RESP-001: Uses consistent envelope structure.
24
+ * INV-MCP-RESP-005: Includes duration tracking.
25
+ */
26
+ export declare function createSuccessResponse<T>(data: T, options?: {
27
+ startTime?: number;
28
+ cached?: boolean;
29
+ truncated?: boolean;
30
+ originalSizeBytes?: number;
31
+ requestId?: string;
32
+ }): MCPToolResult;
33
+ /**
34
+ * Create an error response.
35
+ *
36
+ * INV-MCP-RESP-001: Uses consistent envelope structure.
37
+ * INV-MCP-RESP-002: Includes error code.
38
+ * INV-MCP-RESP-006: Sets retryable based on error code.
39
+ */
40
+ export declare function createErrorResponse(code: MCPErrorCode, message: string, options?: {
41
+ context?: Record<string, unknown>;
42
+ startTime?: number;
43
+ retryAfterMs?: number;
44
+ requestId?: string;
45
+ }): MCPToolResult;
46
+ /**
47
+ * Create a list response with pagination.
48
+ *
49
+ * INV-MCP-RESP-003: Enforces list item limits.
50
+ */
51
+ export declare function createListResponse<T>(items: T[], options?: {
52
+ total?: number;
53
+ limit?: number;
54
+ offset?: number;
55
+ startTime?: number;
56
+ requestId?: string;
57
+ limits?: MCPResponseLimits;
58
+ }): MCPToolResult;
59
+ /**
60
+ * Create a not found error response.
61
+ */
62
+ export declare function createNotFoundResponse(resourceType: string, resourceId: string, options?: {
63
+ startTime?: number;
64
+ requestId?: string;
65
+ }): MCPToolResult;
66
+ /**
67
+ * Create a validation error response.
68
+ */
69
+ export declare function createValidationErrorResponse(message: string, errors: {
70
+ path: string;
71
+ message: string;
72
+ }[], options?: {
73
+ startTime?: number;
74
+ requestId?: string;
75
+ }): MCPToolResult;
76
+ /**
77
+ * Create a timeout error response.
78
+ */
79
+ export declare function createTimeoutResponse(timeoutMs: number, options?: {
80
+ startTime?: number;
81
+ requestId?: string;
82
+ }): MCPToolResult;
83
+ /**
84
+ * Create a memory pressure error response.
85
+ */
86
+ export declare function createMemoryPressureResponse(pressureLevel: string, options?: {
87
+ startTime?: number;
88
+ requestId?: string;
89
+ }): MCPToolResult;
90
+ /**
91
+ * Create an internal error response.
92
+ */
93
+ export declare function createInternalErrorResponse(error: Error, options?: {
94
+ startTime?: number;
95
+ requestId?: string;
96
+ }): MCPToolResult;
97
+ /**
98
+ * Truncate a string to max length.
99
+ *
100
+ * INV-MCP-RESP-003: Enforces string length limits.
101
+ * INV-MCP-RESP-004: Adds truncation indicator.
102
+ */
103
+ export declare function truncateString(str: string, maxLength: number, suffix?: string): {
104
+ text: string;
105
+ truncated: boolean;
106
+ };
107
+ /**
108
+ * Truncate response data to fit within size limits.
109
+ *
110
+ * INV-MCP-RESP-003: Enforces response size limits.
111
+ * INV-MCP-RESP-004: Sets truncated flag.
112
+ */
113
+ export declare function truncateResponse<T>(data: T, limits?: MCPResponseLimits): {
114
+ data: T;
115
+ truncated: boolean;
116
+ originalSizeBytes: number;
117
+ };
118
+ //# sourceMappingURL=helpers.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"helpers.d.ts","sourceRoot":"","sources":["../../src/response/helpers.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,YAAY,EACZ,kBAAkB,EAClB,mBAAmB,EACnB,iBAAiB,EAElB,MAAM,0BAA0B,CAAC;AAYlC,MAAM,WAAW,aAAa;IAC5B,OAAO,EAAE;QACP,IAAI,EAAE,MAAM,CAAC;QACb,IAAI,EAAE,MAAM,CAAC;KACd,EAAE,CAAC;IACJ,OAAO,CAAC,EAAE,OAAO,CAAC;CACnB;AAMD,MAAM,WAAW,mBAAmB,CAAC,CAAC;IACpC,OAAO,EAAE,IAAI,CAAC;IACd,IAAI,EAAE,CAAC,CAAC;IACR,QAAQ,CAAC,EAAE,mBAAmB,CAAC;CAChC;AAED,MAAM,WAAW,iBAAiB;IAChC,OAAO,EAAE,KAAK,CAAC;IACf,KAAK,EAAE,kBAAkB,CAAC;IAC1B,QAAQ,CAAC,EAAE,mBAAmB,CAAC;CAChC;AAED,MAAM,MAAM,YAAY,CAAC,CAAC,IAAI,mBAAmB,CAAC,CAAC,CAAC,GAAG,iBAAiB,CAAC;AAMzE;;;;;GAKG;AACH,wBAAgB,qBAAqB,CAAC,CAAC,EAC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