@maskera/mcp 0.0.0-stage → 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.
@@ -0,0 +1,309 @@
1
+ import { NerRecognizer, NerOptions, RedactionProfile, RedactResult, Detector } from 'maskera';
2
+ import { ServerResponse, Server } from 'node:http';
3
+
4
+ type MaskMode = "auto" | "rules";
5
+ interface EngineOptions {
6
+ /** Default mode when a tool call omits `mode`. Default: `"auto"` (hybrid NER + rules). */
7
+ defaultMode?: MaskMode;
8
+ /** Optional custom NerRecognizer (used in tests or custom deployments). */
9
+ recognizer?: NerRecognizer;
10
+ /** Forwarded to `createNerRecognizer` when no custom recognizer is passed. */
11
+ nerOptions?: NerOptions;
12
+ /**
13
+ * Max entries in the in-memory span cache (stores only SHA-256 digest keys
14
+ * and `{ start, end, label }` offsets, never raw PII text). Default: `512`.
15
+ * Set to `0` to disable caching.
16
+ */
17
+ maxCacheEntries?: number;
18
+ }
19
+ interface RedactInputOptions {
20
+ mode?: MaskMode;
21
+ profile?: RedactionProfile;
22
+ customTerms?: readonly string[];
23
+ }
24
+ interface MaskeraEngine {
25
+ redact(text: string, options?: RedactInputOptions): Promise<{
26
+ result: RedactResult;
27
+ modeUsed: "hybrid" | "rules";
28
+ fallbackReason?: string;
29
+ }>;
30
+ /**
31
+ * Starts loading the local ONNX NER model in the background when defaultMode
32
+ * is `"auto"`. Safe to call on server startup: rejections are captured in
33
+ * `status().nerError` and never cause unhandled promise rejections.
34
+ */
35
+ warmup(): void;
36
+ /** Clears the in-memory span cache. */
37
+ clearCache(): void;
38
+ status(): {
39
+ defaultMode: MaskMode;
40
+ model: string;
41
+ revision: string;
42
+ nerLoaded: boolean;
43
+ nerError: string | null;
44
+ cacheSize: number;
45
+ cacheHits: number;
46
+ cacheMisses: number;
47
+ };
48
+ }
49
+ /**
50
+ * Builds a deterministic, case-insensitive, longest-first detector for caller-
51
+ * supplied custom protected terms (client names, case IDs, codenames).
52
+ */
53
+ declare function buildCustomTermsDetector(rawTerms: readonly string[]): Detector | null;
54
+ declare function createMaskeraEngine(options?: EngineOptions): MaskeraEngine;
55
+
56
+ interface FileGuard {
57
+ readonly allowedRoots: readonly string[];
58
+ readText(filePath: string): Promise<{
59
+ resolvedPath: string;
60
+ content: string;
61
+ bytes: number;
62
+ }>;
63
+ writeText(filePath: string, content: string, options?: {
64
+ overwrite?: boolean;
65
+ }): Promise<{
66
+ resolvedPath: string;
67
+ bytes: number;
68
+ }>;
69
+ }
70
+ /**
71
+ * Confines file reads and writes to explicitly allowed local directories,
72
+ * resolving symlinks to prevent path-traversal escapes and rejecting binary or
73
+ * oversized files.
74
+ */
75
+ declare function createFileGuard(roots?: readonly string[]): FileGuard;
76
+
77
+ interface GuardResult {
78
+ blocked: boolean;
79
+ totalRedactions: number;
80
+ counts: Record<string, number>;
81
+ redacted: string;
82
+ modeUsed: "hybrid" | "rules";
83
+ }
84
+ /**
85
+ * Extracts text from either a plain string or a JSON hook envelope (such as
86
+ * Claude Code / Cursor `UserPromptSubmit`, `PreToolUse`, `PostToolUse`, or
87
+ * `beforeSubmitPrompt` stdin JSON) so the same guard command works across any
88
+ * agent harness or shell pipeline without missing sibling fields or attachments.
89
+ */
90
+ declare function extractGuardText(rawInput: string): {
91
+ text: string;
92
+ isHookEnvelope: boolean;
93
+ };
94
+ declare function runGuard(rawInput: string, engine: MaskeraEngine, options?: {
95
+ mode?: MaskMode;
96
+ profile?: RedactionProfile;
97
+ customTerms?: readonly string[];
98
+ preserveJsonStructure?: boolean;
99
+ }): Promise<GuardResult>;
100
+
101
+ interface InspectedRequest {
102
+ id: string;
103
+ timestamp: string;
104
+ method: string;
105
+ path: string;
106
+ upstream: string;
107
+ sessionId: string;
108
+ status: number;
109
+ streamed: boolean;
110
+ durationMs: number;
111
+ redactions: number;
112
+ counts: Record<string, number>;
113
+ /** Redacted snippets sent upstream (never raw PII). */
114
+ redactedPreview: string[];
115
+ }
116
+ /**
117
+ * In-memory ring buffer and SSE fan-out for the local proxy inspector.
118
+ * Keeps only metadata and already-redacted previews (never raw PII).
119
+ */
120
+ declare class ProxyInspector {
121
+ private readonly items;
122
+ private readonly subscribers;
123
+ private seq;
124
+ record(entry: Omit<InspectedRequest, "id">): InspectedRequest;
125
+ list(): readonly InspectedRequest[];
126
+ clear(): void;
127
+ subscribe(res: ServerResponse, extraHeaders?: Record<string, string>): void;
128
+ closeAll(): void;
129
+ }
130
+ declare function renderInspectorHtml(info: {
131
+ url: string;
132
+ defaultMode: string;
133
+ restoreResponses: boolean;
134
+ }): string;
135
+
136
+ interface SessionSummary {
137
+ sessionId: string;
138
+ entityCount: number;
139
+ countsByLabel: Record<string, number>;
140
+ createdAt: string;
141
+ updatedAt: string;
142
+ }
143
+ /**
144
+ * Process-local, in-memory restore vault keyed by session_id.
145
+ *
146
+ * Keeps raw PII values inside the local MCP process so an agent can mask
147
+ * multiple documents under one session (receiving consistent `[NAMN_1]`
148
+ * numbering across files) and later write restored output directly to disk
149
+ * without ever exposing raw values to the cloud LLM.
150
+ */
151
+ declare class SessionVault {
152
+ private readonly sessions;
153
+ private readonly maxSessions;
154
+ private readonly maxEntitiesPerSession;
155
+ constructor(maxSessions?: number, maxEntitiesPerSession?: number);
156
+ private getOrCreate;
157
+ /**
158
+ * Re-number a RedactResult's replacements into a persistent session so that
159
+ * the same entity receives the exact same placeholder across multiple calls
160
+ * and files in the same session, while avoiding collisions with literal text.
161
+ */
162
+ apply(originalInput: string, result: RedactResult, sessionId?: string): {
163
+ sessionId: string;
164
+ redacted: string;
165
+ counts: Record<string, number>;
166
+ totalRedactions: number;
167
+ map: Record<string, string>;
168
+ };
169
+ restore(text: string, options: {
170
+ sessionId?: string;
171
+ map?: Record<string, string>;
172
+ }): {
173
+ restored: string;
174
+ sessionId: string | null;
175
+ knownPlaceholders: number;
176
+ };
177
+ getMap(sessionId: string): Record<string, string>;
178
+ entries(): Array<{
179
+ sessionId: string;
180
+ token: string;
181
+ value: string;
182
+ }>;
183
+ clearAll(): void;
184
+ list(): SessionSummary[];
185
+ clear(sessionId: string): boolean;
186
+ get size(): number;
187
+ }
188
+
189
+ interface ProxyOptions {
190
+ /** Bind address. Defaults to loopback `127.0.0.1` for local safety. */
191
+ host?: string;
192
+ /** Listening port. Defaults to `8787` (`0` picks an ephemeral port). */
193
+ port?: number;
194
+ /** Explicit upstream base URL (overrides automatic Anthropic/OpenAI routing). */
195
+ upstream?: string;
196
+ /** Upstream URL for Anthropic routes when `upstream` is unset. */
197
+ anthropicUpstream?: string;
198
+ /** Upstream URL for OpenAI routes when `upstream` is unset. */
199
+ openaiUpstream?: string;
200
+ /** Optional custom MaskeraEngine. */
201
+ engine?: MaskeraEngine;
202
+ /** Optional custom SessionVault. */
203
+ vault?: SessionVault;
204
+ /** Default mode if creating a new engine (`"auto"` or `"rules"`). */
205
+ defaultMode?: MaskMode;
206
+ /** Optional built-in precision profile (`"general"` or `"clinical"`). */
207
+ profile?: RedactionProfile;
208
+ /** Optional extra protected terms (client names, codenames, case IDs). */
209
+ customTerms?: readonly string[];
210
+ /** Restore placeholders in upstream responses. Default `true`. */
211
+ restoreResponses?: boolean;
212
+ /** Optional local JSONL file for metadata-only audit logs (counts only, never raw PII). */
213
+ auditLogPath?: string;
214
+ /** Optional safe metadata logger (never receives raw PII). */
215
+ onLog?: (message: string) => void;
216
+ }
217
+ interface RunningMaskeraProxy {
218
+ readonly url: string;
219
+ readonly inspectorUrl: string;
220
+ readonly host: string;
221
+ readonly port: number;
222
+ readonly server: Server;
223
+ readonly vault: SessionVault;
224
+ readonly inspector: ProxyInspector;
225
+ close(): Promise<void>;
226
+ }
227
+ /**
228
+ * Incremental placeholder restorer for streamed LLM responses (SSE deltas).
229
+ *
230
+ * Holds back only a tiny trailing suffix when it is a prefix of a known
231
+ * placeholder (e.g. `"[NAM"` while waiting for `"N_1]"`), flushing all safe
232
+ * characters immediately so streaming stays low-latency without dropping
233
+ * split placeholders.
234
+ */
235
+ declare class StreamingRestorer {
236
+ private buffer;
237
+ private readonly tokens;
238
+ private readonly map;
239
+ private readonly maxTokenLength;
240
+ private readonly escapeForJsonString;
241
+ constructor(map: Readonly<Record<string, string>>, options?: {
242
+ escapeForJsonString?: boolean;
243
+ });
244
+ private formatReplacement;
245
+ push(chunk: string): string;
246
+ flush(): string;
247
+ private drain;
248
+ }
249
+ type RedactFieldKind = "message" | "system" | "tool_description";
250
+ /**
251
+ * Redacts all user/tool/system text fields in an Anthropic Messages, OpenAI
252
+ * Chat Completions, or OpenAI Responses request body before it leaves the
253
+ * local machine.
254
+ */
255
+ declare function redactLlmRequestBody(body: Record<string, unknown>, redactString: (text: string, kind: RedactFieldKind) => Promise<string>, options?: {
256
+ mutate?: boolean;
257
+ }): Promise<Record<string, unknown>>;
258
+ /**
259
+ * Restores Maskera placeholders in a non-streaming Anthropic or OpenAI JSON
260
+ * response without touching IDs, model names, or usage metadata.
261
+ */
262
+ declare function restoreLlmResponseBody(body: unknown, map: Readonly<Record<string, string>>, options?: {
263
+ mutate?: boolean;
264
+ }): unknown;
265
+ /**
266
+ * Transforms an SSE (`text/event-stream`) stream from Anthropic or OpenAI,
267
+ * incrementally restoring Maskera placeholders even when split across chunks.
268
+ */
269
+ declare function createSseRestorer(map: Readonly<Record<string, string>>): {
270
+ push(chunk: string): string;
271
+ flush(): string;
272
+ };
273
+ /**
274
+ * Starts a local, harness-agnostic LLM HTTP reverse proxy.
275
+ *
276
+ * Point `ANTHROPIC_BASE_URL`, `OPENAI_BASE_URL`, or any OpenAI/Anthropic SDK
277
+ * at this proxy to automatically redact Swedish PII locally before prompts or
278
+ * tool results leave the machine, and transparently restore placeholders in
279
+ * both JSON and SSE streaming responses.
280
+ */
281
+ declare function startMaskeraProxy(options?: ProxyOptions): Promise<RunningMaskeraProxy>;
282
+
283
+ declare const SERVER_NAME = "maskera-mcp";
284
+ declare const SERVER_VERSION = "0.2.0";
285
+ interface JsonRpcResponse {
286
+ jsonrpc: "2.0";
287
+ id: string | number | null;
288
+ result?: unknown;
289
+ error?: {
290
+ code: number;
291
+ message: string;
292
+ data?: unknown;
293
+ };
294
+ }
295
+ interface MaskeraMcpOptions {
296
+ engine?: MaskeraEngine;
297
+ vault?: SessionVault;
298
+ files?: FileGuard;
299
+ allowedRoots?: readonly string[];
300
+ defaultProfile?: RedactionProfile;
301
+ defaultCustomTerms?: readonly string[];
302
+ }
303
+ interface MaskeraMcpServer {
304
+ handleMessage(raw: unknown): Promise<JsonRpcResponse | null>;
305
+ readonly vault: SessionVault;
306
+ }
307
+ declare function createMaskeraMcpServer(options?: MaskeraMcpOptions): MaskeraMcpServer;
308
+
309
+ export { type EngineOptions, type FileGuard, type GuardResult, type InspectedRequest, type JsonRpcResponse, type MaskMode, type MaskeraEngine, type MaskeraMcpOptions, type MaskeraMcpServer, ProxyInspector, type ProxyOptions, type RedactFieldKind, type RedactInputOptions, type RunningMaskeraProxy, SERVER_NAME, SERVER_VERSION, type SessionSummary, SessionVault, StreamingRestorer, buildCustomTermsDetector, createFileGuard, createMaskeraEngine, createMaskeraMcpServer, createSseRestorer, extractGuardText, redactLlmRequestBody, renderInspectorHtml, restoreLlmResponseBody, runGuard, startMaskeraProxy };