@waswrongassembled/pii-shield 0.0.0-stage → 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.
Files changed (127) hide show
  1. package/CHANGELOG.md +29 -0
  2. package/LICENSE +22 -0
  3. package/README.md +276 -2
  4. package/dist/ai-sdk/index.d.ts +19 -0
  5. package/dist/ai-sdk/index.js +30 -0
  6. package/dist/ai-sdk/middleware.d.ts +63 -0
  7. package/dist/ai-sdk/middleware.js +388 -0
  8. package/dist/bin.d.ts +2 -0
  9. package/dist/bin.js +9 -0
  10. package/dist/cli.d.ts +2 -0
  11. package/dist/cli.js +124 -0
  12. package/dist/detector.d.ts +28 -0
  13. package/dist/detector.js +3 -0
  14. package/dist/detectors/at-svnr.d.ts +14 -0
  15. package/dist/detectors/at-svnr.js +31 -0
  16. package/dist/detectors/authority-context.d.ts +22 -0
  17. package/dist/detectors/authority-context.js +278 -0
  18. package/dist/detectors/birth-date.d.ts +10 -0
  19. package/dist/detectors/birth-date.js +21 -0
  20. package/dist/detectors/email.d.ts +15 -0
  21. package/dist/detectors/email.js +29 -0
  22. package/dist/detectors/file-number.d.ts +16 -0
  23. package/dist/detectors/file-number.js +20 -0
  24. package/dist/detectors/iban.d.ts +10 -0
  25. package/dist/detectors/iban.js +41 -0
  26. package/dist/detectors/license-plate.d.ts +9 -0
  27. package/dist/detectors/license-plate.js +13 -0
  28. package/dist/detectors/phone.d.ts +13 -0
  29. package/dist/detectors/phone.js +38 -0
  30. package/dist/detectors/postal-address.d.ts +14 -0
  31. package/dist/detectors/postal-address.js +19 -0
  32. package/dist/detectors/salutation-person.d.ts +18 -0
  33. package/dist/detectors/salutation-person.js +37 -0
  34. package/dist/detectors/tax-number.d.ts +14 -0
  35. package/dist/detectors/tax-number.js +33 -0
  36. package/dist/entity-extractor.d.ts +47 -0
  37. package/dist/entity-extractor.js +245 -0
  38. package/dist/entity-type.d.ts +24 -0
  39. package/dist/entity-type.js +26 -0
  40. package/dist/entity.d.ts +28 -0
  41. package/dist/entity.js +11 -0
  42. package/dist/errors.d.ts +48 -0
  43. package/dist/errors.js +49 -0
  44. package/dist/index.d.ts +42 -0
  45. package/dist/index.js +40 -0
  46. package/dist/internal/pcre.d.ts +55 -0
  47. package/dist/internal/pcre.js +102 -0
  48. package/dist/internal/php-json.d.ts +15 -0
  49. package/dist/internal/php-json.js +48 -0
  50. package/dist/internal/placeholder-stream.d.ts +24 -0
  51. package/dist/internal/placeholder-stream.js +118 -0
  52. package/dist/internal/text-spans.d.ts +8 -0
  53. package/dist/internal/text-spans.js +15 -0
  54. package/dist/learning/char-set.d.ts +29 -0
  55. package/dist/learning/char-set.js +158 -0
  56. package/dist/learning/custom-entity-detector.d.ts +26 -0
  57. package/dist/learning/custom-entity-detector.js +70 -0
  58. package/dist/learning/custom-entity-type.d.ts +49 -0
  59. package/dist/learning/custom-entity-type.js +150 -0
  60. package/dist/learning/entity-learner.d.ts +50 -0
  61. package/dist/learning/entity-learner.js +87 -0
  62. package/dist/learning/json-file-store.d.ts +36 -0
  63. package/dist/learning/json-file-store.js +132 -0
  64. package/dist/learning/learned-pattern.d.ts +48 -0
  65. package/dist/learning/learned-pattern.js +640 -0
  66. package/dist/learning/pattern-grammar.d.ts +12 -0
  67. package/dist/learning/pattern-grammar.js +148 -0
  68. package/dist/learning/pattern-learner.d.ts +10 -0
  69. package/dist/learning/pattern-learner.js +116 -0
  70. package/dist/learning/store.d.ts +51 -0
  71. package/dist/learning/store.js +84 -0
  72. package/dist/masking/partial-mask.d.ts +23 -0
  73. package/dist/masking/partial-mask.js +43 -0
  74. package/dist/masking/strategy.d.ts +10 -0
  75. package/dist/masking/strategy.js +1 -0
  76. package/dist/masking/type-label-mask.d.ts +17 -0
  77. package/dist/masking/type-label-mask.js +28 -0
  78. package/dist/mcp/index.d.ts +33 -0
  79. package/dist/mcp/index.js +146 -0
  80. package/dist/mcp/tools.d.ts +63 -0
  81. package/dist/mcp/tools.js +183 -0
  82. package/dist/model/chunks.d.ts +13 -0
  83. package/dist/model/chunks.js +74 -0
  84. package/dist/model/model-detector.d.ts +110 -0
  85. package/dist/model/model-detector.js +420 -0
  86. package/dist/model/prompt.d.ts +16 -0
  87. package/dist/model/prompt.js +192 -0
  88. package/dist/pii-masker.d.ts +27 -0
  89. package/dist/pii-masker.js +56 -0
  90. package/dist/pii-shield.d.ts +40 -0
  91. package/dist/pii-shield.js +142 -0
  92. package/dist/placeholder.d.ts +48 -0
  93. package/dist/placeholder.js +138 -0
  94. package/dist/redaction.d.ts +76 -0
  95. package/dist/redaction.js +52 -0
  96. package/dist/server/config.d.ts +23 -0
  97. package/dist/server/config.js +187 -0
  98. package/dist/server/http-server.d.ts +63 -0
  99. package/dist/server/http-server.js +241 -0
  100. package/dist/server/index.d.ts +9 -0
  101. package/dist/server/index.js +9 -0
  102. package/dist/server/model-providers.d.ts +31 -0
  103. package/dist/server/model-providers.js +158 -0
  104. package/dist/service/json-body.d.ts +14 -0
  105. package/dist/service/json-body.js +35 -0
  106. package/dist/service/local-peer.d.ts +16 -0
  107. package/dist/service/local-peer.js +83 -0
  108. package/dist/service/service-api.d.ts +75 -0
  109. package/dist/service/service-api.js +305 -0
  110. package/dist/validators/at-svnr.d.ts +8 -0
  111. package/dist/validators/at-svnr.js +21 -0
  112. package/dist/validators/de-tax-id.d.ts +8 -0
  113. package/dist/validators/de-tax-id.js +35 -0
  114. package/dist/validators/iban.d.ts +5 -0
  115. package/dist/validators/iban.js +24 -0
  116. package/dist/vault/encrypted-vault.d.ts +37 -0
  117. package/dist/vault/encrypted-vault.js +152 -0
  118. package/dist/vault/in-memory-vault.d.ts +17 -0
  119. package/dist/vault/in-memory-vault.js +39 -0
  120. package/dist/vault/memory-vault-storage.d.ts +16 -0
  121. package/dist/vault/memory-vault-storage.js +37 -0
  122. package/dist/vault/vault.d.ts +38 -0
  123. package/dist/vault/vault.js +16 -0
  124. package/dist/vault-redis/index.d.ts +28 -0
  125. package/dist/vault-redis/index.js +33 -0
  126. package/docs/openapi.yaml +422 -0
  127. package/package.json +122 -4
@@ -0,0 +1,146 @@
1
+ /**
2
+ * @waswrongassembled/pii-shield/mcp: the pii-shield MCP server (optional peer `@modelcontextprotocol/sdk`).
3
+ *
4
+ * Tools `redact_text`, `restore_text`, `mask_text`, `learn_entity_type` and `list_entity_types`, as in
5
+ * PHP's PiiShieldTools, over STDIO or Streamable HTTP. The mapping stays on the server: redact_text
6
+ * returns placeholders and a vaultId. restore_text returns the original values to the MCP client, and in
7
+ * an agent the client is the model: call it only where the model may see the data.
8
+ */
9
+ import { randomUUID } from 'node:crypto';
10
+ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
11
+ import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
12
+ import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';
13
+ import { CallToolRequestSchema, ErrorCode, isInitializeRequest, ListToolsRequestSchema, } from '@modelcontextprotocol/sdk/types.js';
14
+ import { callTool, InvalidToolCall, SERVER_INFO, SERVER_INSTRUCTIONS, TOOLS } from './tools.js';
15
+ export { callTool, InvalidToolCall, SERVER_INFO, SERVER_INSTRUCTIONS, TOOLS, } from './tools.js';
16
+ /**
17
+ * An MCP server with the pii-shield tools on top of a ServiceApi. One server serves one transport
18
+ * (connect it with `server.connect(transport)`); the API can be shared.
19
+ */
20
+ export function createMcpServer(api) {
21
+ const mcp = new McpServer(SERVER_INFO, { capabilities: { tools: {} }, instructions: SERVER_INSTRUCTIONS });
22
+ // The low-level handlers keep PHP's exact JSON schemas (McpServer.registerTool() wants zod schemas).
23
+ mcp.server.setRequestHandler(ListToolsRequestSchema, () => ({
24
+ tools: TOOLS.map((tool) => structuredClone(tool)),
25
+ }));
26
+ mcp.server.setRequestHandler(CallToolRequestSchema, async (request, extra) => {
27
+ try {
28
+ return await callTool(api, request.params.name, request.params.arguments, { signal: extra.signal });
29
+ }
30
+ catch (e) {
31
+ if (e instanceof InvalidToolCall) {
32
+ throw rpcError(ErrorCode.InvalidParams, e.message);
33
+ }
34
+ if (extra.signal.aborted) {
35
+ throw e;
36
+ }
37
+ throw rpcError(ErrorCode.InternalError, 'Error while executing tool');
38
+ }
39
+ });
40
+ return mcp;
41
+ }
42
+ /**
43
+ * Serves the tools over STDIO (for Claude Code, Claude Desktop, the MCP Inspector). Nothing else may
44
+ * write to stdout while it runs; log to stderr. Resolves with the server once connected.
45
+ */
46
+ export async function serveStdio(api, options = {}) {
47
+ const server = createMcpServer(api);
48
+ await server.connect(new StdioServerTransport(options.stdin, options.stdout));
49
+ return server;
50
+ }
51
+ /**
52
+ * Streamable HTTP for `startServer({ mcp })` / `createRequestListener({ mcp })`, which guard /mcp like
53
+ * /v1 (host names, origin, JSON, bearer token or local peer). Stateful: `initialize` opens a session
54
+ * (`Mcp-Session-Id`), each session has its own server; answers are JSON, not SSE.
55
+ */
56
+ export function createMcpHttpHandler(api, options = {}) {
57
+ const { sessionIdleMs = 3_600_000, maxSessions = 1000, maxBodyBytes = 2 * 1024 * 1024 } = options;
58
+ const sessions = new Map();
59
+ const closeSession = async (id) => {
60
+ const session = sessions.get(id);
61
+ sessions.delete(id);
62
+ await session?.server.close();
63
+ };
64
+ const sweep = async () => {
65
+ const now = Date.now();
66
+ const doomed = new Set([...sessions].filter(([, s]) => now - s.usedAt > sessionIdleMs).map(([id]) => id));
67
+ // Map order is insertion order and used sessions are re-inserted: the first is the least recently used.
68
+ for (const id of sessions.keys()) {
69
+ if (sessions.size - doomed.size < maxSessions) {
70
+ break;
71
+ }
72
+ doomed.add(id);
73
+ }
74
+ await Promise.all([...doomed].map(closeSession));
75
+ };
76
+ return {
77
+ async handle(req, res) {
78
+ const header = req.headers['mcp-session-id'];
79
+ const id = Array.isArray(header) ? header[0] : header;
80
+ const session = id === undefined ? undefined : sessions.get(id);
81
+ if (session !== undefined && id !== undefined) {
82
+ sessions.delete(id);
83
+ session.usedAt = Date.now();
84
+ sessions.set(id, session);
85
+ await session.transport.handleRequest(req, res);
86
+ return;
87
+ }
88
+ if (id !== undefined || req.method !== 'POST') {
89
+ sendRpcError(res, id === undefined ? 400 : 404, id === undefined ? 'Bad Request: No valid session ID provided' : 'Session not found');
90
+ return;
91
+ }
92
+ const body = await readJson(req, maxBodyBytes);
93
+ if (body === undefined ||
94
+ !(Array.isArray(body) ? body.some((m) => isInitializeRequest(m)) : isInitializeRequest(body))) {
95
+ sendRpcError(res, 400, 'Bad Request: No valid session ID provided');
96
+ return;
97
+ }
98
+ await sweep();
99
+ const server = createMcpServer(api);
100
+ const transport = new StreamableHTTPServerTransport({
101
+ sessionIdGenerator: () => randomUUID(),
102
+ enableJsonResponse: true,
103
+ maxRequestBodySize: maxBodyBytes,
104
+ onsessioninitialized: (sessionId) => {
105
+ sessions.set(sessionId, { transport, server, usedAt: Date.now() });
106
+ },
107
+ onsessionclosed: (sessionId) => {
108
+ sessions.delete(sessionId);
109
+ },
110
+ });
111
+ await server.connect(transport);
112
+ await transport.handleRequest(req, res, body);
113
+ },
114
+ async close() {
115
+ await Promise.all([...sessions.keys()].map(closeSession));
116
+ },
117
+ };
118
+ }
119
+ /**
120
+ * A JSON-RPC error with exactly this message (McpError would prefix "MCP error <code>: " on the wire).
121
+ */
122
+ function rpcError(code, message) {
123
+ return Object.assign(new Error(message), { code });
124
+ }
125
+ async function readJson(req, limit) {
126
+ const chunks = [];
127
+ let size = 0;
128
+ for await (const chunk of req) {
129
+ size += chunk.length;
130
+ if (size > limit) {
131
+ return undefined;
132
+ }
133
+ chunks.push(chunk);
134
+ }
135
+ try {
136
+ return JSON.parse(Buffer.concat(chunks).toString('utf8'));
137
+ }
138
+ catch {
139
+ return undefined;
140
+ }
141
+ }
142
+ function sendRpcError(res, status, message) {
143
+ const json = JSON.stringify({ jsonrpc: '2.0', error: { code: -32000, message }, id: null });
144
+ res.writeHead(status, { 'Content-Type': 'application/json' });
145
+ res.end(json);
146
+ }
@@ -0,0 +1,63 @@
1
+ import type { ServiceApi } from '../service/service-api.js';
2
+ /** JSON Schema of a tool's arguments (the subset these tools use). */
3
+ interface PropertySchema {
4
+ readonly type: 'string' | 'array' | 'boolean';
5
+ readonly description: string;
6
+ readonly default?: unknown;
7
+ readonly enum?: readonly string[];
8
+ readonly pattern?: string;
9
+ readonly items?: {
10
+ readonly type: 'string';
11
+ };
12
+ }
13
+ export interface ToolDefinition {
14
+ readonly name: string;
15
+ readonly title: string;
16
+ readonly description: string;
17
+ readonly inputSchema: {
18
+ readonly type: 'object';
19
+ readonly properties: Readonly<Record<string, PropertySchema>>;
20
+ readonly required?: readonly string[];
21
+ };
22
+ readonly annotations: Readonly<Record<string, boolean>>;
23
+ }
24
+ /**
25
+ * The tools of PHP's PiiShieldTools: same names, titles, descriptions, input schemas and annotations
26
+ * (as PHP's MCP SDK generates them).
27
+ */
28
+ export declare const TOOLS: readonly ToolDefinition[];
29
+ /** Server info and instructions of PHP's MCP server configuration. */
30
+ export declare const SERVER_INFO: Readonly<{
31
+ name: "pii-shield";
32
+ version: "1.0.0";
33
+ description: "Reversible redaction, masking and learning of personal data.";
34
+ }>;
35
+ export declare const SERVER_INSTRUCTIONS = "Before giving text with personal data to a model, call redact_text and work with the placeholders. restore_text returns the original values to you, the calling model: call it only if you run locally or the user asked for the restored text; otherwise give the user the answer with placeholders and the vaultId to restore it themselves.";
36
+ /** Result of a tool call (MCP CallToolResult). */
37
+ export type ToolResult = {
38
+ content: [{
39
+ type: 'text';
40
+ text: string;
41
+ }];
42
+ structuredContent: Record<string, unknown>;
43
+ isError?: never;
44
+ } | {
45
+ content: [{
46
+ type: 'text';
47
+ text: string;
48
+ }];
49
+ isError: true;
50
+ };
51
+ /** A protocol error (JSON-RPC "invalid params"), e.g. unknown tool or arguments that violate the schema. */
52
+ export declare class InvalidToolCall extends Error {
53
+ }
54
+ /**
55
+ * Runs a tool like PHP's PiiShieldTools: the arguments are checked against the input schema (an
56
+ * InvalidToolCall with the first violation), then the ServiceApi operation runs. An API error (status
57
+ * >= 400) becomes a tool result with `isError`, so the model sees the message; success returns the JSON
58
+ * body as pretty-printed text and as `structuredContent`.
59
+ */
60
+ export declare function callTool(api: ServiceApi, name: string, args: Readonly<Record<string, unknown>> | undefined, options?: {
61
+ signal?: AbortSignal | undefined;
62
+ }): Promise<ToolResult>;
63
+ export {};
@@ -0,0 +1,183 @@
1
+ import { encodeJson } from '../learning/json-file-store.js';
2
+ /**
3
+ * The tools of PHP's PiiShieldTools: same names, titles, descriptions, input schemas and annotations
4
+ * (as PHP's MCP SDK generates them).
5
+ */
6
+ export const TOOLS = Object.freeze([
7
+ {
8
+ name: 'redact_text',
9
+ title: 'Redact personal data',
10
+ description: 'Replaces personal data (names, addresses, IDs, IBANs, …) with placeholders such as ⟦PERSON_1⟧, so the text can be given to any model. Returns the redacted text, a vaultId for restore_text and the placeholder types; never the original values.',
11
+ inputSchema: {
12
+ type: 'object',
13
+ properties: {
14
+ text: { type: 'string', description: 'Text with personal data, e.g. a letter.' },
15
+ detection: {
16
+ type: 'string',
17
+ default: 'regex',
18
+ description: "regex (patterns, offline), model (the server's configured model) or both.",
19
+ enum: ['regex', 'model', 'both'],
20
+ },
21
+ },
22
+ required: ['text'],
23
+ },
24
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false },
25
+ },
26
+ {
27
+ name: 'restore_text',
28
+ title: 'Restore placeholders',
29
+ description: 'Puts the original values back into a text with placeholders (typically a model answer), using the vaultId from redact_text. Placeholders the model invented are reported.',
30
+ inputSchema: {
31
+ type: 'object',
32
+ properties: {
33
+ text: { type: 'string', description: 'Text containing placeholders like ⟦PERSON_1⟧.' },
34
+ vaultId: { type: 'string', description: 'vaultId returned by redact_text.' },
35
+ },
36
+ required: ['text', 'vaultId'],
37
+ },
38
+ annotations: { readOnlyHint: true, openWorldHint: false },
39
+ },
40
+ {
41
+ name: 'mask_text',
42
+ title: 'Mask personal data irreversibly',
43
+ description: 'Masks personal data for logs and previews (e.g. AT61 **** **** **** 3201, [PERSON]). Nothing is stored; there is no way back.',
44
+ inputSchema: {
45
+ type: 'object',
46
+ properties: { text: { type: 'string', description: 'Text with personal data.' } },
47
+ required: ['text'],
48
+ },
49
+ annotations: { readOnlyHint: true, openWorldHint: false },
50
+ },
51
+ {
52
+ name: 'learn_entity_type',
53
+ title: 'Learn a new kind of personal data',
54
+ description: 'Teaches pii-shield a new entity type from examples ("mask things like this too"). A pattern is derived from the examples; plain words become model-only types. Use synthetic examples only: they are stored. dryRun previews without saving.',
55
+ inputSchema: {
56
+ type: 'object',
57
+ properties: {
58
+ name: {
59
+ type: 'string',
60
+ description: 'UPPER_SNAKE_CASE name, becomes the placeholder name, e.g. INSURANCE_NUMBER.',
61
+ pattern: '^[A-Z][A-Z0-9_]{1,39}$',
62
+ },
63
+ examples: { type: 'array', description: 'Examples of the value, one per item.', items: { type: 'string' } },
64
+ description: { type: 'string', default: '', description: 'What it is; helps the model.' },
65
+ counterExamples: {
66
+ type: 'array',
67
+ default: [],
68
+ description: 'Similar values that are not this type.',
69
+ items: { type: 'string' },
70
+ },
71
+ dryRun: { type: 'boolean', default: false, description: 'Only derive and validate, do not save.' },
72
+ },
73
+ required: ['name', 'examples'],
74
+ },
75
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false },
76
+ },
77
+ {
78
+ name: 'list_entity_types',
79
+ title: 'List learned entity types',
80
+ description: 'Lists the entity types learned from examples, with their patterns.',
81
+ inputSchema: { type: 'object', properties: {} },
82
+ annotations: { readOnlyHint: true, openWorldHint: false },
83
+ },
84
+ ]);
85
+ /** Server info and instructions of PHP's MCP server configuration. */
86
+ export const SERVER_INFO = Object.freeze({
87
+ name: 'pii-shield',
88
+ version: '1.0.0',
89
+ description: 'Reversible redaction, masking and learning of personal data.',
90
+ });
91
+ export const SERVER_INSTRUCTIONS = 'Before giving text with personal data to a model, call redact_text and work with the placeholders. restore_text returns the original values to you, the calling model: call it only if you run locally or the user asked for the restored text; otherwise give the user the answer with placeholders and the vaultId to restore it themselves.';
92
+ /** A protocol error (JSON-RPC "invalid params"), e.g. unknown tool or arguments that violate the schema. */
93
+ export class InvalidToolCall extends Error {
94
+ }
95
+ const TOOL_OPERATIONS = {
96
+ redact_text: (a) => ['redact', { text: a['text'], detection: a['detection'] ?? 'regex' }],
97
+ restore_text: (a) => ['restore', { text: a['text'], vaultId: a['vaultId'] }],
98
+ mask_text: (a) => ['mask', { text: a['text'] }],
99
+ learn_entity_type: (a) => [
100
+ 'learn',
101
+ {
102
+ name: a['name'],
103
+ description: a['description'] ?? '',
104
+ examples: a['examples'],
105
+ counterExamples: a['counterExamples'] ?? [],
106
+ dryRun: a['dryRun'] ?? false,
107
+ },
108
+ ],
109
+ list_entity_types: () => ['entities', {}],
110
+ };
111
+ /**
112
+ * Runs a tool like PHP's PiiShieldTools: the arguments are checked against the input schema (an
113
+ * InvalidToolCall with the first violation), then the ServiceApi operation runs. An API error (status
114
+ * >= 400) becomes a tool result with `isError`, so the model sees the message; success returns the JSON
115
+ * body as pretty-printed text and as `structuredContent`.
116
+ */
117
+ export async function callTool(api, name, args, options = {}) {
118
+ const tool = TOOLS.find((t) => t.name === name);
119
+ const toOperation = Object.hasOwn(TOOL_OPERATIONS, name) ? TOOL_OPERATIONS[name] : undefined;
120
+ if (tool === undefined || toOperation === undefined) {
121
+ throw new InvalidToolCall(`Tool not found: "${name}".`);
122
+ }
123
+ const values = args ?? {};
124
+ const violation = validate(tool, values);
125
+ if (violation !== null) {
126
+ throw new InvalidToolCall(`Invalid parameters for tool '${name}': ${violation}`);
127
+ }
128
+ const [operation, body] = toOperation(values);
129
+ const response = await api.operation(operation, body, { signal: options.signal });
130
+ if (response.status >= 400) {
131
+ const error = response.body?.['error'];
132
+ return {
133
+ content: [{ type: 'text', text: typeof error === 'string' ? error : 'The operation failed.' }],
134
+ isError: true,
135
+ };
136
+ }
137
+ const result = response.body ?? {};
138
+ return { content: [{ type: 'text', text: encodeJson(result) }], structuredContent: { ...result } };
139
+ }
140
+ /** The first schema violation in the wording of PHP's MCP SDK (opis/json-schema), or null. */
141
+ function validate(tool, args) {
142
+ const { properties, required = [] } = tool.inputSchema;
143
+ const missing = required.filter((key) => !Object.hasOwn(args, key));
144
+ if (missing.length > 0) {
145
+ return `Missing required properties: ${missing.map((k) => `\`${k}\``).join(', ')}.`;
146
+ }
147
+ for (const [key, schema] of Object.entries(properties)) {
148
+ if (!Object.hasOwn(args, key)) {
149
+ continue;
150
+ }
151
+ const value = args[key];
152
+ const pointer = `Property '/${key}': `;
153
+ if (jsonType(value) !== schema.type) {
154
+ return `${pointer}Invalid type. Expected \`${schema.type}\`, but received \`${jsonType(value)}\`.`;
155
+ }
156
+ if (schema.enum !== undefined && !schema.enum.includes(value)) {
157
+ return `${pointer}Value must be one of the allowed values: ${schema.enum.map((v) => JSON.stringify(v)).join(', ')}.`;
158
+ }
159
+ if (schema.pattern !== undefined && !new RegExp(schema.pattern, 'u').test(value)) {
160
+ return `${pointer}String does not match the required pattern: \`${schema.pattern}\`.`;
161
+ }
162
+ if (schema.items !== undefined) {
163
+ const items = value;
164
+ const index = items.findIndex((item) => jsonType(item) !== schema.items?.type);
165
+ if (index !== -1) {
166
+ return `Property '/${key}/${String(index)}': Invalid type. Expected \`${schema.items.type}\`, but received \`${jsonType(items[index])}\`.`;
167
+ }
168
+ }
169
+ }
170
+ return null;
171
+ }
172
+ function jsonType(value) {
173
+ if (value === null) {
174
+ return 'null';
175
+ }
176
+ if (Array.isArray(value)) {
177
+ return 'array';
178
+ }
179
+ if (typeof value === 'number') {
180
+ return Number.isInteger(value) ? 'integer' : 'number';
181
+ }
182
+ return typeof value;
183
+ }
@@ -0,0 +1,13 @@
1
+ /** More chunks fail closed instead of fanning out (about 200,000 characters at the default size). */
2
+ export declare const MAX_CHUNKS = 50;
3
+ /**
4
+ * Splits a text into chunks of at most `size` code points: a window over the original text, cut at the
5
+ * last paragraph break in its second half, else the last line break, else the last space. Each chunk
6
+ * starts an overlap of the window before the previous end (at a word start), wherever the cut was, so a
7
+ * value shorter than the overlap is always sent whole in at least one chunk.
8
+ *
9
+ * @throws DetectionError before anything is sent, if the text needs more than MAX_CHUNKS chunks
10
+ *
11
+ * @internal
12
+ */
13
+ export declare function chunks(text: string, size: number): string[];
@@ -0,0 +1,74 @@
1
+ import { DetectionError } from '../errors.js';
2
+ import { codePointLength } from '../internal/pcre.js';
3
+ /** More chunks fail closed instead of fanning out (about 200,000 characters at the default size). */
4
+ export const MAX_CHUNKS = 50;
5
+ /** Each chunk repeats the last fifth of the previous one. */
6
+ const OVERLAP_DIVISOR = 5;
7
+ const SEPARATORS = [['\n', '\n'], ['\n'], [' ']];
8
+ const WORD_BREAKS = new Set([' ', '\n', '\t']);
9
+ /**
10
+ * Splits a text into chunks of at most `size` code points: a window over the original text, cut at the
11
+ * last paragraph break in its second half, else the last line break, else the last space. Each chunk
12
+ * starts an overlap of the window before the previous end (at a word start), wherever the cut was, so a
13
+ * value shorter than the overlap is always sent whole in at least one chunk.
14
+ *
15
+ * @throws DetectionError before anything is sent, if the text needs more than MAX_CHUNKS chunks
16
+ *
17
+ * @internal
18
+ */
19
+ export function chunks(text, size) {
20
+ // Each chunk advances by at least a tenth of the size: decide before splitting a huge text.
21
+ const length = codePointLength(text);
22
+ if (length > MAX_CHUNKS * size) {
23
+ throw tooLong(Math.floor(length / size) + 1, size);
24
+ }
25
+ if (length <= size) {
26
+ return [text];
27
+ }
28
+ const chars = Array.from(text);
29
+ const overlap = Math.floor(size / OVERLAP_DIVISOR);
30
+ const result = [];
31
+ let start = 0;
32
+ for (;;) {
33
+ let end = Math.min(length, start + size);
34
+ if (end < length) {
35
+ for (const separator of SEPARATORS) {
36
+ const cut = lastIndexOf(chars, start, end, separator);
37
+ if (cut !== -1 && cut >= Math.floor((end - start) / 2)) {
38
+ end = start + cut + separator.length;
39
+ break;
40
+ }
41
+ }
42
+ }
43
+ result.push(chars.slice(start, end).join(''));
44
+ if (end >= length) {
45
+ return result;
46
+ }
47
+ // Back to a word start, but only within one more overlap: text without spaces must still
48
+ // advance by at least a tenth of the size per chunk (cut in the second half, minus 2 overlaps).
49
+ let next = end - overlap;
50
+ const limit = Math.max(start + 1, end - 2 * overlap);
51
+ while (next > limit && !WORD_BREAKS.has(chars[next - 1] ?? '')) {
52
+ next--;
53
+ }
54
+ if (next <= limit) {
55
+ next = end - overlap;
56
+ }
57
+ start = Math.max(start + 1, next);
58
+ if (result.length >= MAX_CHUNKS) {
59
+ throw tooLong(result.length + 1, size);
60
+ }
61
+ }
62
+ }
63
+ /** Position of the last `separator` inside chars[start, end), relative to start (mb_strrpos()), or -1. */
64
+ function lastIndexOf(chars, start, end, separator) {
65
+ for (let i = end - separator.length; i >= start; i--) {
66
+ if (separator.every((c, j) => chars[i + j] === c)) {
67
+ return i - start;
68
+ }
69
+ }
70
+ return -1;
71
+ }
72
+ function tooLong(count, size) {
73
+ return new DetectionError(`The text is too long for model-based detection: at least ${String(count)} chunks of ${String(size)} characters, at most ${String(MAX_CHUNKS)}.`, 'DETECTION_TEXT_TOO_LONG');
74
+ }
@@ -0,0 +1,110 @@
1
+ import type { AsyncDetector, DetectOptions } from '../detector.js';
2
+ import { type Entity } from '../entity.js';
3
+ import type { CustomEntityType } from '../learning/custom-entity-type.js';
4
+ import { EntityLearner } from '../learning/entity-learner.js';
5
+ import type { CustomEntityStore } from '../learning/store.js';
6
+ /**
7
+ * Where the detection model runs (PHP's ModelLocation, same values). Detection necessarily sends the
8
+ * unredacted text to the model, so this decides whether personal data leaves your infrastructure.
9
+ *
10
+ * - `local`: the same machine, e.g. Ollama on localhost.
11
+ * - `on_premise`: your own infrastructure, e.g. a GPU server running Ollama or vLLM.
12
+ * - `external`: a third-party provider (OpenAI, Anthropic, Mistral, ...). Needs a data processing
13
+ * agreement, possibly a third-country transfer; requires `acknowledgeExternalTransfer: true`.
14
+ */
15
+ export declare const ModelLocation: Readonly<{
16
+ readonly Local: "local";
17
+ readonly OnPremise: "on_premise";
18
+ readonly External: "external";
19
+ }>;
20
+ export type ModelLocation = (typeof ModelLocation)[keyof typeof ModelLocation];
21
+ /** The two messages of one model call: the instructions and a chunk of the unredacted text. */
22
+ export interface ModelPrompt {
23
+ readonly system: string;
24
+ readonly user: string;
25
+ }
26
+ export interface ModelCallOptions {
27
+ /** Aborted when the caller cancels, the timeout passes or another chunk of the same text failed. */
28
+ readonly signal: AbortSignal;
29
+ }
30
+ /**
31
+ * Calls a model and returns its text answer. Wrap any provider SDK in it; for the Vercel AI SDK use
32
+ * `detectionModel()` from `@waswrongassembled/pii-shield/ai-sdk`.
33
+ */
34
+ export type ModelFunction = (prompt: ModelPrompt, options: ModelCallOptions) => Promise<string>;
35
+ /** A model function with the name used in error messages (e.g. "llama3.1:8b"). */
36
+ export interface DetectionModel {
37
+ readonly name: string;
38
+ readonly generate: ModelFunction;
39
+ }
40
+ export interface ModelDetectorOptions {
41
+ /** The model: a function, or a DetectionModel to name it in error messages. */
42
+ model: ModelFunction | DetectionModel;
43
+ /** Where the model runs; required, because detection sends the unredacted text there. */
44
+ location: ModelLocation;
45
+ /** Required for `location: 'external'` (data processing agreement, possibly a third-country transfer). */
46
+ acknowledgeExternalTransfer?: boolean;
47
+ /**
48
+ * Learned types, taught to the model with their examples (also model-only types without a pattern).
49
+ * A store is read at every detect() call (as in PHP); an EntityLearner gives its snapshot.
50
+ */
51
+ learnedTypes?: CustomEntityStore | EntityLearner | Iterable<CustomEntityType>;
52
+ /** Code points per model call, at least 100. Default ModelDetector.DEFAULT_CHUNK_SIZE (4,000). */
53
+ chunkSize?: number;
54
+ /** Keep the sender authority's contacts (letterhead, "erreichen Sie uns unter ..."). Default true. */
55
+ keepAuthorityContacts?: boolean;
56
+ /** Milliseconds a detect() call may take in total; then it fails with DETECTION_MODEL_UNREACHABLE. */
57
+ timeout?: number;
58
+ }
59
+ /**
60
+ * Detects personal data with a model of your choice: a local Ollama, an on-premise GPU server or a
61
+ * public provider. Works for any language and country, not only DACH formats. Port of PHP's
62
+ * `ModelDetector`: same prompt, same parsing, same checks.
63
+ *
64
+ * - The model returns type + value; every value is grounded in the original text (whitespace and
65
+ * commas may differ). Values the model invented are dropped.
66
+ * - Findings are checked in their context with the rules of the pattern detectors (dates, citations,
67
+ * file number keywords, authority contacts); addresses are extended by the postcode and town that follow.
68
+ * - Long texts go out in overlapping chunks, four at a time. An unusable answer is asked for once more,
69
+ * then detection fails closed with DetectionError.
70
+ *
71
+ * Async: use it with `PiiShield.redactAsync()`, `redactToVault()`, `PiiMasker.maskAsync()` or
72
+ * `EntityExtractor.extractAsync()`, next to the regex detectors (checksum-validated findings win on overlap).
73
+ * Errors never contain the text; nothing is logged.
74
+ */
75
+ export declare class ModelDetector implements AsyncDetector {
76
+ #private;
77
+ static readonly DEFAULT_CHUNK_SIZE = 4000;
78
+ static readonly MAX_CHUNKS = 50;
79
+ readonly name = "model";
80
+ readonly async = true;
81
+ readonly location: ModelLocation;
82
+ /**
83
+ * @throws RangeError for a chunk size below 100 or an invalid timeout
84
+ * @throws TypeError for an empty model name, an unknown location, or an external location without acknowledgement
85
+ */
86
+ constructor(options: ModelDetectorOptions);
87
+ /**
88
+ * Entities sorted by offset (UTF-16). Rejects with the signal's reason when the caller aborts.
89
+ *
90
+ * @throws DetectionError
91
+ */
92
+ detect(text: string, options?: DetectOptions): Promise<Entity[]>;
93
+ }
94
+ /**
95
+ * PHP: '/§§?[ \t]*\d+[a-z]?(?:[ \t]+(?:Abs|lit|Z|Ziff|Satz|Nr|Art)\.?[ \t]*\w+\)?)*[ \t]+$/u' on the line before.
96
+ *
97
+ * As a regex this backtracks exponentially in JavaScript ("Ziff" is "Z" + "iff" or a keyword of its own,
98
+ * so " Ziff Ziff Ziff ..." has Fibonacci many parses). Each part is otherwise deterministic, so a
99
+ * right-to-left pass decides it in linear time: good[i] says whether the line from i on is a sequence of
100
+ * citation parts followed by blanks up to its end.
101
+ *
102
+ * @internal exported for tests
103
+ */
104
+ export declare function isAfterCitation(before: string): boolean;
105
+ /**
106
+ * PHP: '/\b'.KEYWORDS.'[ \t]*:?[ \t]*$/u'; the blanks and the colon are stripped first (linear).
107
+ *
108
+ * @internal exported for tests
109
+ */
110
+ export declare function isAfterFileNumberKeyword(before: string): boolean;