@maskera/mcp 0.2.0 → 0.3.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/dist/index.d.ts CHANGED
@@ -1,6 +1,53 @@
1
1
  import { NerRecognizer, NerOptions, RedactionProfile, RedactResult, Detector } from 'maskera';
2
2
  import { ServerResponse, Server } from 'node:http';
3
3
 
4
+ type ApprovalMode = "automatic" | "browser" | "native";
5
+ type ApprovalStatus = "pending" | "approved" | "declined" | "expired" | "completed";
6
+ interface ApprovalSummary {
7
+ id: string;
8
+ tool: string;
9
+ reason: string;
10
+ sessionId: string | null;
11
+ placeholderCount: number;
12
+ status: ApprovalStatus;
13
+ createdAt: string;
14
+ expiresAt: string;
15
+ decidedAt: string | null;
16
+ }
17
+ type ApprovalResumeResult = {
18
+ status: "completed";
19
+ result: Record<string, unknown>;
20
+ summary: ApprovalSummary;
21
+ } | {
22
+ status: "pending" | "declined" | "expired" | "not_found";
23
+ summary?: ApprovalSummary;
24
+ };
25
+ /**
26
+ * Process-local approval broker for sensitive MCP actions that would return
27
+ * raw PII into model context (such as `maskera_restore` or `maskera_redact`
28
+ * with `include_map: true`). Summaries never store or emit raw PII values.
29
+ */
30
+ declare class ApprovalBroker {
31
+ private readonly records;
32
+ private readonly listeners;
33
+ private readonly ttlMs;
34
+ constructor(ttlMs?: number);
35
+ private expireStale;
36
+ private notify;
37
+ onChange(listener: (summaries: ApprovalSummary[]) => void): () => void;
38
+ create(input: {
39
+ tool: string;
40
+ reason: string;
41
+ sessionId?: string | null;
42
+ placeholderCount: number;
43
+ execute: () => Promise<Record<string, unknown>>;
44
+ }): ApprovalSummary;
45
+ list(): ApprovalSummary[];
46
+ decide(id: string, decision: "approve" | "decline"): ApprovalSummary | null;
47
+ resume(id: string): Promise<ApprovalResumeResult>;
48
+ clearAll(): void;
49
+ }
50
+
4
51
  type MaskMode = "auto" | "rules";
5
52
  interface EngineOptions {
6
53
  /** Default mode when a tool call omits `mode`. Default: `"auto"` (hybrid NER + rules). */
@@ -53,6 +100,36 @@ interface MaskeraEngine {
53
100
  declare function buildCustomTermsDetector(rawTerms: readonly string[]): Detector | null;
54
101
  declare function createMaskeraEngine(options?: EngineOptions): MaskeraEngine;
55
102
 
103
+ type DoctorCheckStatus = "ok" | "warn" | "fail";
104
+ interface DoctorCheck {
105
+ name: string;
106
+ status: DoctorCheckStatus;
107
+ detail: string;
108
+ }
109
+ interface DoctorReport {
110
+ ok: boolean;
111
+ mode: MaskMode;
112
+ checks: DoctorCheck[];
113
+ }
114
+ declare function runDoctor(options: {
115
+ engine: MaskeraEngine;
116
+ roots: readonly string[];
117
+ mode?: MaskMode;
118
+ profile?: RedactionProfile;
119
+ customTerms?: readonly string[];
120
+ proxyUrl?: string;
121
+ }): Promise<DoctorReport>;
122
+ declare function formatDoctorReport(report: DoctorReport): string;
123
+
124
+ interface ListedFile {
125
+ path: string;
126
+ bytes: number;
127
+ }
128
+ interface SearchMatch {
129
+ path: string;
130
+ line: number;
131
+ lineText: string;
132
+ }
56
133
  interface FileGuard {
57
134
  readonly allowedRoots: readonly string[];
58
135
  readText(filePath: string): Promise<{
@@ -66,11 +143,30 @@ interface FileGuard {
66
143
  resolvedPath: string;
67
144
  bytes: number;
68
145
  }>;
146
+ listFiles(dirPath?: string, options?: {
147
+ maxEntries?: number;
148
+ maxDepth?: number;
149
+ }): Promise<{
150
+ root: string;
151
+ files: ListedFile[];
152
+ truncated: boolean;
153
+ }>;
154
+ searchFiles(query: string, options?: {
155
+ path?: string;
156
+ caseSensitive?: boolean;
157
+ maxMatches?: number;
158
+ maxFiles?: number;
159
+ }): Promise<{
160
+ root: string;
161
+ scannedFiles: number;
162
+ matches: SearchMatch[];
163
+ truncated: boolean;
164
+ }>;
69
165
  }
70
166
  /**
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.
167
+ * Confines file reads, writes, directory listings, and searches to explicitly
168
+ * allowed local directories, resolving symlinks to prevent path-traversal
169
+ * escapes and rejecting binary or oversized files.
74
170
  */
75
171
  declare function createFileGuard(roots?: readonly string[]): FileGuard;
76
172
 
@@ -114,14 +210,16 @@ interface InspectedRequest {
114
210
  redactedPreview: string[];
115
211
  }
116
212
  /**
117
- * In-memory ring buffer and SSE fan-out for the local proxy inspector.
213
+ * In-memory ring buffer and SSE fan-out for the local proxy and MCP inspector.
118
214
  * Keeps only metadata and already-redacted previews (never raw PII).
119
215
  */
120
216
  declare class ProxyInspector {
121
217
  private readonly items;
122
218
  private readonly subscribers;
219
+ private approvalsSnapshot;
123
220
  private seq;
124
221
  record(entry: Omit<InspectedRequest, "id">): InspectedRequest;
222
+ publishApprovals(approvals: ApprovalSummary[]): void;
125
223
  list(): readonly InspectedRequest[];
126
224
  clear(): void;
127
225
  subscribe(res: ServerResponse, extraHeaders?: Record<string, string>): void;
@@ -129,10 +227,43 @@ declare class ProxyInspector {
129
227
  }
130
228
  declare function renderInspectorHtml(info: {
131
229
  url: string;
230
+ mcpUrl?: string;
132
231
  defaultMode: string;
133
232
  restoreResponses: boolean;
134
233
  }): string;
135
234
 
235
+ declare const SUPPORTED_CLIENTS: readonly ["claude-code", "claude-desktop", "codex", "cursor", "opencode", "t3-code"];
236
+ type InstallClient = (typeof SUPPORTED_CLIENTS)[number];
237
+ type InstallTransport = "stdio" | "http";
238
+ interface InstallOptions {
239
+ client: InstallClient;
240
+ transport?: InstallTransport;
241
+ mcpUrl?: string;
242
+ roots?: readonly string[];
243
+ noRawRestore?: boolean;
244
+ readOnly?: boolean;
245
+ approvalMode?: ApprovalMode;
246
+ rulesOnly?: boolean;
247
+ profile?: RedactionProfile;
248
+ customTerms?: readonly string[];
249
+ configPath?: string;
250
+ dryRun?: boolean;
251
+ cwd?: string;
252
+ homeDir?: string;
253
+ platform?: NodeJS.Platform;
254
+ }
255
+ interface InstallResult {
256
+ client: InstallClient;
257
+ transport: InstallTransport;
258
+ configPath: string | null;
259
+ command: string | null;
260
+ snippet: string;
261
+ written: boolean;
262
+ verifyStep: string;
263
+ }
264
+ declare function isInstallClient(value: string): value is InstallClient;
265
+ declare function runInstall(options: InstallOptions): Promise<InstallResult>;
266
+
136
267
  interface SessionSummary {
137
268
  sessionId: string;
138
269
  entityCount: number;
@@ -201,6 +332,16 @@ interface ProxyOptions {
201
332
  engine?: MaskeraEngine;
202
333
  /** Optional custom SessionVault. */
203
334
  vault?: SessionVault;
335
+ /** Optional custom ApprovalBroker for browser MCP approvals. */
336
+ approvals?: ApprovalBroker;
337
+ /** Allowed workspace roots for the co-hosted Streamable HTTP `/mcp` endpoint. */
338
+ mcpRoots?: readonly string[];
339
+ /** Allow `maskera_restore` / `include_map: true` over `/mcp`. Default `true`. */
340
+ allowRawRestore?: boolean;
341
+ /** Disable file writes and session clears over `/mcp`. Default `false`. */
342
+ readOnly?: boolean;
343
+ /** Default approval mode for `/mcp` raw PII exports. Default `"automatic"`. */
344
+ approvalMode?: ApprovalMode;
204
345
  /** Default mode if creating a new engine (`"auto"` or `"rules"`). */
205
346
  defaultMode?: MaskMode;
206
347
  /** Optional built-in precision profile (`"general"` or `"clinical"`). */
@@ -216,12 +357,14 @@ interface ProxyOptions {
216
357
  }
217
358
  interface RunningMaskeraProxy {
218
359
  readonly url: string;
360
+ readonly mcpUrl: string;
219
361
  readonly inspectorUrl: string;
220
362
  readonly host: string;
221
363
  readonly port: number;
222
364
  readonly server: Server;
223
365
  readonly vault: SessionVault;
224
366
  readonly inspector: ProxyInspector;
367
+ readonly approvals: ApprovalBroker;
225
368
  close(): Promise<void>;
226
369
  }
227
370
  /**
@@ -276,12 +419,13 @@ declare function createSseRestorer(map: Readonly<Record<string, string>>): {
276
419
  * Point `ANTHROPIC_BASE_URL`, `OPENAI_BASE_URL`, or any OpenAI/Anthropic SDK
277
420
  * at this proxy to automatically redact Swedish PII locally before prompts or
278
421
  * tool results leave the machine, and transparently restore placeholders in
279
- * both JSON and SSE streaming responses.
422
+ * both JSON and SSE streaming responses. Also serves Streamable HTTP MCP on
423
+ * `/mcp` sharing the same warm ONNX model, session vault, and live inspector.
280
424
  */
281
425
  declare function startMaskeraProxy(options?: ProxyOptions): Promise<RunningMaskeraProxy>;
282
426
 
283
427
  declare const SERVER_NAME = "maskera-mcp";
284
- declare const SERVER_VERSION = "0.2.0";
428
+ declare const SERVER_VERSION = "0.3.0";
285
429
  interface JsonRpcResponse {
286
430
  jsonrpc: "2.0";
287
431
  id: string | number | null;
@@ -292,18 +436,75 @@ interface JsonRpcResponse {
292
436
  data?: unknown;
293
437
  };
294
438
  }
295
- interface MaskeraMcpOptions {
439
+ interface ElicitationRequest {
440
+ message: string;
441
+ requestedSchema: Record<string, unknown>;
442
+ }
443
+ interface ElicitationResponse {
444
+ action: "accept" | "decline" | "cancel";
445
+ content?: Record<string, unknown>;
446
+ }
447
+ interface ToolCallTelemetry {
448
+ tool: string;
449
+ sessionId?: string;
450
+ redactions: number;
451
+ counts: Record<string, number>;
452
+ durationMs: number;
453
+ isError: boolean;
454
+ }
455
+ interface MaskeraMcpPolicy {
456
+ /** Block `maskera_restore` and `maskera_redact(..., { include_map: true })`. Default: `true` (allowed). */
457
+ allowRawRestore?: boolean;
458
+ /** Omit and block state-changing tools (`maskera_write_file`, `maskera_clear_session`). Default: `false`. */
459
+ readOnly?: boolean;
460
+ /** Gate raw PII release (`automatic`, `browser`, or `native` MCP elicitation). Default: `"automatic"`. */
461
+ approvalMode?: ApprovalMode;
462
+ }
463
+ interface MaskeraMcpOptions extends MaskeraMcpPolicy {
296
464
  engine?: MaskeraEngine;
297
465
  vault?: SessionVault;
298
466
  files?: FileGuard;
299
467
  allowedRoots?: readonly string[];
300
468
  defaultProfile?: RedactionProfile;
301
469
  defaultCustomTerms?: readonly string[];
470
+ approvals?: ApprovalBroker;
471
+ approvalBaseUrl?: string;
472
+ requestElicitation?: (req: ElicitationRequest) => Promise<ElicitationResponse>;
473
+ onToolCall?: (event: ToolCallTelemetry) => void;
302
474
  }
303
475
  interface MaskeraMcpServer {
304
- handleMessage(raw: unknown): Promise<JsonRpcResponse | null>;
476
+ handleMessage(raw: unknown, policyOverride?: MaskeraMcpPolicy): Promise<JsonRpcResponse | null>;
305
477
  readonly vault: SessionVault;
306
478
  }
307
479
  declare function createMaskeraMcpServer(options?: MaskeraMcpOptions): MaskeraMcpServer;
308
480
 
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 };
481
+ declare const MASKERA_SKILL_URI = "maskera://skills/maskera/SKILL.md";
482
+ declare const MASKERA_STATUS_URI = "maskera://status";
483
+ /**
484
+ * Bundled Maskera agent workflow skill served directly over MCP resources and
485
+ * prompts so connected clients get the full operating guide without a separate
486
+ * skill install step. Kept in sync with `skills/maskera/SKILL.md` by unit test.
487
+ */
488
+ declare const MASKERA_SKILL_MARKDOWN = "---\nname: maskera\ndescription: Redact Swedish personal data (names, personnummer, addresses, phones, emails, IBAN, org numbers) locally before text or files reach an AI model, and restore answers locally. Use when working with Swedish client files, HR/CVs, legal or municipal cases, healthcare notes, support transcripts, or when setting up @maskera/mcp (local LLM proxy, Streamable HTTP or stdio MCP server, guard) or the maskera npm SDK.\n---\n\n# Maskera: local Swedish PII redaction\n\nMaskera runs 100% locally on-device using deterministic Swedish rules plus the 43 MB Swedish ONNX NER model (`joelhagvall/maskera-sv-ner`). Raw PII and restore maps stay local so cloud LLMs only see placeholders such as `[NAMN_1]` and `[PERSONNUMMER_1]`.\n\n## Choose the right mode\n\nPick by where the text comes from: **proxy for text typed straight into the chat**, **MCP for files the agent reads with the Maskera tools**. Before the user sends real personal data, verify the setup with made-up data (a fictional address) and confirm a placeholder in the local inspector at `http://127.0.0.1:8787/_maskera`, or run `npx -y @maskera/mcp doctor`.\n\n1. **Local LLM proxy + warm Streamable HTTP MCP (`maskera-mcp proxy`):**\n Use when no prompt, history or tool output may leave the machine unredacted, or when multiple clients should share one warm ONNX model and session vault.\n ```bash\n npx -y @maskera/mcp proxy --root /path/to/workspace\n # Point any harness or SDK at the loopback proxy:\n ANTHROPIC_BASE_URL=http://127.0.0.1:8787 claude\n OPENAI_BASE_URL=http://127.0.0.1:8787/v1 codex # API key mode; ChatGPT-login Codex requires HTTPS so use MCP below\n # Same warm process also serves Streamable HTTP MCP:\n # http://127.0.0.1:8787/mcp (supports ?no_raw_restore=1&read_only=1&approval_mode=browser)\n ```\n - Claude Desktop: Help -> Troubleshooting -> Enable Developer Mode, then Developer -> Configure Third-Party Inference. Set Inference provider to **Gateway**, Credential kind **Static API key**, Gateway base URL `http://127.0.0.1:8787` (no `/v1`), Gateway API key = the user's Anthropic API key, Gateway auth scheme **x-api-key**. Apply Changes, then Save & Restart. Full guide: `https://maskera.dev/docs/guides`.\n - Routes Anthropic (`/v1/messages`) and OpenAI (`/v1/chat/completions`, `/v1/responses`) automatically, or set `--upstream <url>`.\n - Restores placeholders transparently in JSON, tool arguments and chunk-split SSE streams.\n - Fails closed (`502`) if local redaction fails. Inspect counts only at `http://127.0.0.1:8787/_maskera/status`.\n\n2. **Working with sensitive local Swedish files (MCP stdio or Streamable HTTP):**\n Install automatically with `npx -y @maskera/mcp install <client>` (`claude-code`, `claude-desktop`, `codex`, `cursor`, `opencode`, `t3-code`), or configure manually:\n - Claude Code / Cursor (`mcpServers`):\n ```json\n {\n \"mcpServers\": {\n \"maskera\": {\n \"command\": \"npx\",\n \"args\": [\"-y\", \"@maskera/mcp\", \"--root\", \"/path/to/workspace\", \"--no-raw-restore\"]\n }\n }\n }\n ```\n - Codex CLI:\n ```bash\n codex mcp add maskera -- npx -y @maskera/mcp --root /path/to/workspace --no-raw-restore\n ```\n - OpenCode v2:\n ```bash\n opencode mcp add maskera -- npx -y @maskera/mcp --root /path/to/workspace --no-raw-restore\n ```\n Workflow rules when the Maskera MCP tools are available:\n - List and search sensitive Swedish directories with `maskera_list_files` and `maskera_search_files` instead of raw `grep`/`rg` so matched lines are redacted before entering context.\n - Read sensitive Swedish files with `maskera_read_file` instead of raw file-reading tools. Reuse one `session_id` across related files so `[NAMN_1]` stays consistent.\n - Pass `custom_terms` for client codenames, project names or case references not covered by built-in rules.\n - Pass `profile: \"clinical\"` for Swedish medical or care notes so diagnoses, doses and measurements stay intact while personal data is masked.\n - Write finished drafts directly to disk with `maskera_write_file` so placeholders are restored locally without echoing raw PII back into the conversation.\n - Use `--no-raw-restore` (or `--approval-mode browser`) when the agent should never pull raw PII back into chat via `maskera_restore` or `include_map: true`.\n - Clear the in-memory restore map with `maskera_clear_session` once the task is done.\n\n3. **Hooks and Unix pipes (guard):**\n ```bash\n # Block prompts or JSON hook payloads containing PII (exits 2, prints counts only):\n npx -y @maskera/mcp guard\n # Redact text locally in a pipeline:\n cat input.txt | npx -y @maskera/mcp guard --redact\n ```\n\n4. **Embedding in application code (browser or Node 18+):**\n ```bash\n npm install maskera @huggingface/transformers\n ```\n Reuse one `createNerRecognizer()` instance across calls and run `await redactWithNer(text, { recognizer })` (or `redact(text)` from `@maskera/core` for zero-dependency structured rules only).\n\n## Boundaries\n\n- A skill guides agent behaviour; for hard enforcement that cannot be bypassed by raw shell or file tools, use `maskera-mcp proxy` or restrict file access to `maskera-mcp` with `--no-raw-restore`.\n- Automated masking reduces exposure risk but is not a zero-leak guarantee. Never log restore maps or write them next to redacted outputs.\n- Reference docs and machine-readable details: `https://maskera.dev/docs` and `https://maskera.dev/llms.txt`.\n";
489
+ interface McpPromptDefinition {
490
+ name: string;
491
+ description: string;
492
+ arguments?: Array<{
493
+ name: string;
494
+ description: string;
495
+ required?: boolean;
496
+ }>;
497
+ }
498
+ declare const MASKERA_PROMPTS: readonly McpPromptDefinition[];
499
+ declare function renderMaskeraPrompt(name: string, args: Record<string, unknown>): {
500
+ description: string;
501
+ messages: Array<{
502
+ role: "user";
503
+ content: {
504
+ type: "text";
505
+ text: string;
506
+ };
507
+ }>;
508
+ } | null;
509
+
510
+ export { ApprovalBroker, type ApprovalMode, type ApprovalResumeResult, type ApprovalStatus, type ApprovalSummary, type DoctorCheck, type DoctorCheckStatus, type DoctorReport, type ElicitationRequest, type ElicitationResponse, type EngineOptions, type FileGuard, type GuardResult, type InspectedRequest, type InstallClient, type InstallOptions, type InstallResult, type InstallTransport, type JsonRpcResponse, type ListedFile, MASKERA_PROMPTS, MASKERA_SKILL_MARKDOWN, MASKERA_SKILL_URI, MASKERA_STATUS_URI, type MaskMode, type MaskeraEngine, type MaskeraMcpOptions, type MaskeraMcpPolicy, type MaskeraMcpServer, type McpPromptDefinition, ProxyInspector, type ProxyOptions, type RedactFieldKind, type RedactInputOptions, type RunningMaskeraProxy, SERVER_NAME, SERVER_VERSION, SUPPORTED_CLIENTS, type SearchMatch, type SessionSummary, SessionVault, StreamingRestorer, type ToolCallTelemetry, buildCustomTermsDetector, createFileGuard, createMaskeraEngine, createMaskeraMcpServer, createSseRestorer, extractGuardText, formatDoctorReport, isInstallClient, redactLlmRequestBody, renderInspectorHtml, renderMaskeraPrompt, restoreLlmResponseBody, runDoctor, runGuard, runInstall, startMaskeraProxy };