@webdecoy/ai-protection 0.1.0-alpha.6 → 0.1.0-alpha.7

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 (4) hide show
  1. package/MCP.md +45 -1
  2. package/mcp.d.mts +8 -1
  3. package/mcp.mjs +37 -4
  4. package/package.json +1 -1
package/MCP.md CHANGED
@@ -11,7 +11,7 @@ resource authorization.
11
11
  Available in `0.1.0-alpha.5` and later compatible alpha releases:
12
12
 
13
13
  ```sh
14
- npm install @webdecoy/ai-protection@0.1.0-alpha.5 @modelcontextprotocol/sdk@1.31.0
14
+ npm install @webdecoy/ai-protection@0.1.0-alpha.7 @modelcontextprotocol/sdk@1.31.0
15
15
  ```
16
16
 
17
17
  Requires Node 22.22.3+ and MCP SDK **1.31.0**. The MCP SDK is an optional peer, so
@@ -120,3 +120,47 @@ whole MCP server. See the [MCP transport specification](https://modelcontextprot
120
120
  and [authorization specification](https://modelcontextprotocol.io/specification/2025-11-25/basic/authorization).
121
121
 
122
122
  For weighted search/export limits and tenant concurrency, see [bounded tool work](WORK.md).
123
+
124
+
125
+ ## Opt-in tool discovery (alpha.7+)
126
+
127
+ Add these options alongside your existing `tools` and authentication configuration:
128
+
129
+ ```ts
130
+ sharedRuntime: {
131
+ webdecoyUrl: 'https://ai-protection.webdecoy.com',
132
+ webdecoyKey: process.env.WEBDECOY_API_KEY!,
133
+ propertyId: process.env.WEBDECOY_PROPERTY_ID!,
134
+ subjectSecret: process.env.WEBDECOY_SUBJECT_SECRET!, // at least 32 bytes
135
+ },
136
+ discovery: { serverId: 'records-api' },
137
+ ```
138
+
139
+ Use a stable, non-secret server label (1–96 letters, digits, `_`, `.`, `:`, `-`,
140
+ starting with a letter or digit). Reuse it across replicas/releases of the same
141
+ logical server. Give separate servers separate labels within a property. Do not
142
+ include tenant IDs, hostnames containing secrets, or customer information.
143
+
144
+ An authenticated MCP client calls `tools/list`. Each nonempty response queues a
145
+ best-effort advertisement of the visible tool names and SHA-256 input-schema
146
+ hashes. The AI Protection dashboard shows **Advertised MCP tools**, including
147
+ tools that have never executed. This does not scan unwrapped servers, hidden tools,
148
+ resources, prompts or alternate routes. No network request is made at handler
149
+ construction. Discovery is off unless configured and requires sharedRuntime.
150
+
151
+ Hashes cover the JSON input schema with recursively sorted object keys; array
152
+ order is preserved. Raw schemas, descriptions, arguments, results, credentials,
153
+ caller identities and required scopes are not uploaded. A schema hash is a
154
+ fingerprint, not encryption; someone with a candidate schema can compare it.
155
+ Multiple hashes for one server/tool show reported variants in the seven-day
156
+ receipt window. Rolling deployments and benign schema edits can cause variants.
157
+ They do not establish an attack, breaking change, removal or missing permission.
158
+ The UI uses the latest receipt's hash, not a claim about deployment order.
159
+
160
+ Discovery uses schema-3 reports on the existing reporting endpoint; deploy a
161
+ compatible hosted runtime first. Old runtimes reject these optional reports
162
+ without affecting tool listing. Reporting has bounded pending work and a deadline,
163
+ never blocks authorization, and does not retry. Call `await handler.flush()` at a
164
+ host shutdown/lifecycle boundary to drain pending discovery reports; it does not
165
+ wait for active tool calls or action reports. Abruptly terminated hosts can lose
166
+ reports. Discovery advertisements never increment tool action or request counts.
package/mcp.d.mts CHANGED
@@ -21,6 +21,10 @@ export interface ProtectedMCPOptions {
21
21
  policyVersion: string;
22
22
  sharedRuntime?: ActionRuntime;
23
23
  tools: Record<string, ProtectedTool>;
24
+ /** Opt-in tools/list metadata: stable non-secret server label and SHA-256 input-schema hashes.
25
+ * Requires sharedRuntime. Reuse serverId across replicas; separate different servers.
26
+ */
27
+ discovery?: { serverId: string };
24
28
  /** Exact browser origins; requests without Origin are permitted after authentication. */
25
29
  allowedOrigins?: string[];
26
30
  /** Best-effort, sanitized action events. */
@@ -33,4 +37,7 @@ export interface ProtectedMCPOptions {
33
37
  * Does not wrap existing MCP servers, resources, prompts, tasks or alternate routes.
34
38
  */
35
39
  export function createProtectedMCPHandler(options: ProtectedMCPOptions):
36
- (request: IncomingMessage, response: ServerResponse) => Promise<void>;
40
+ ((request: IncomingMessage, response: ServerResponse) => Promise<void>) & {
41
+ /** Drain pending discovery reports at shutdown. Does not wait for running tools. */
42
+ flush(): Promise<void>;
43
+ };
package/mcp.mjs CHANGED
@@ -2,6 +2,8 @@ import { Server } from '@modelcontextprotocol/sdk/server/index.js';
2
2
  import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';
3
3
  import { CallToolRequestSchema, ListToolsRequestSchema, ErrorCode, McpError } from '@modelcontextprotocol/sdk/types.js';
4
4
  import { createActionProtection, ActionDenied } from './actions.mjs';
5
+ import { createHash, randomUUID } from 'node:crypto';
6
+ import { createReporter } from './reporting.mjs';
5
7
  const metadataPath = '/.well-known/oauth-protected-resource/mcp';
6
8
  export function createProtectedMCPHandler(options) {
7
9
  const resource = new URL(options.resource), issuer = new URL(options.authorizationServer);
@@ -16,12 +18,40 @@ export function createProtectedMCPHandler(options) {
16
18
  for (const scope of tool.requiredScopes)
17
19
  if (!/^[\x21\x23-\x5b\x5d-\x7e]+$/.test(scope))
18
20
  throw Error('Invalid OAuth scope');
21
+ // Opt-in metadata only. Never collect descriptions, raw schemas, scopes,
22
+ // credentials, arguments or resource URLs in discovery reports.
23
+ if (options.discovery !== undefined && (!options.sharedRuntime || !options.discovery ||
24
+ !/^[a-zA-Z0-9][a-zA-Z0-9_.:-]{0,95}$/.test(options.discovery.serverId)))
25
+ throw Error('Discovery requires sharedRuntime and a stable serverId');
26
+ const canonical = value => {
27
+ if (value === null || typeof value !== 'object') return JSON.stringify(value);
28
+ if (Array.isArray(value)) return '[' + value.map(canonical).join(',') + ']';
29
+ return '{' + Object.keys(value).sort().map(key => JSON.stringify(key) + ':' + canonical(value[key])).join(',') + '}';
30
+ };
31
+ const hashes = options.discovery ? Object.fromEntries(Object.entries(tools).map(([name, tool]) =>
32
+ [name, createHash('sha256').update(canonical(JSON.parse(JSON.stringify(tool.inputSchema)))).digest('hex')])) : {};
33
+ const runtime = options.sharedRuntime && { ...options.sharedRuntime };
34
+ const serverId = options.discovery?.serverId;
35
+ const catalogReporter = options.discovery ? createReporter({
36
+ reportingTimeoutMs: runtime.reportingTimeoutMs ?? 1000,
37
+ maxPendingReports: runtime.maxPendingReports ?? 100,
38
+ onObservation: async (names, { signal }) => {
39
+ const response = await fetch(new URL('/api/v1/sdk/ai-abuse/reports', runtime.webdecoyUrl), {
40
+ method: 'POST', redirect: 'error', signal,
41
+ headers: { Authorization: `Bearer ${runtime.webdecoyKey}`, 'X-WebDecoy-Property-ID': runtime.propertyId, 'Content-Type': 'application/json' },
42
+ body: JSON.stringify({ schema: 3, request_id: randomUUID(), timestamp: new Date().toISOString(), action: 'tool_discovery',
43
+ tool_catalog: { server_id: serverId, source: 'tools_list', tools: names.map(name => ({ name, schema_hash: hashes[name] })) } })
44
+ });
45
+ await response.body?.cancel();
46
+ if (!response.ok) throw Error('Discovery reporting unavailable');
47
+ }
48
+ }) : null;
19
49
  const active = new Map();
20
50
  const scopes = [...new Set(Object.values(tools).flatMap(t => t.requiredScopes))];
21
51
  const origins = new Set(options.allowedOrigins ?? []);
22
52
  function respond(res, status, error, headers = {}) { res.writeHead(status, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store', ...headers }); res.end(JSON.stringify({ error })); }
23
53
  function challenge(res, status, scope) { respond(res, status, status === 401 ? 'unauthorized' : 'insufficient_scope', { 'WWW-Authenticate': `Bearer resource_metadata="${metadataURL}"${status === 401 ? '' : `, error="insufficient_scope", scope="${scope.join(' ')}"`}` }); }
24
- return async function handle(req, res) {
54
+ const handle = async function (req, res) {
25
55
  const disconnected = new AbortController();
26
56
  req.once('aborted', () => disconnected.abort());
27
57
  res.once('close', () => { if (!res.writableEnded)
@@ -163,9 +193,11 @@ export function createProtectedMCPHandler(options) {
163
193
  const server = new Server({ name: 'webdecoy-protected-tools', version: '0.1.0' }, { capabilities: { tools: {} } });
164
194
  const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: undefined, enableJsonResponse: false });
165
195
  res.once('close', () => { void server.close().catch(() => { }); });
166
- server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: Object.entries(tools)
167
- .filter(([, tool]) => tool.requiredScopes.every(s => caller.scopes.includes(s)))
168
- .map(([name, tool]) => ({ name, description: tool.description, inputSchema: tool.inputSchema })) }));
196
+ server.setRequestHandler(ListToolsRequestSchema, async () => {
197
+ const visible = Object.entries(tools).filter(([, tool]) => tool.requiredScopes.every(s => caller.scopes.includes(s)));
198
+ if (visible.length) void catalogReporter?.send(visible.map(([name]) => name));
199
+ return { tools: visible.map(([name, tool]) => ({ name, description: tool.description, inputSchema: tool.inputSchema })) };
200
+ });
169
201
  server.setRequestHandler(CallToolRequestSchema, async (request, extra) => {
170
202
  if (!Object.hasOwn(tools, request.params.name))
171
203
  throw new McpError(ErrorCode.InvalidParams, 'Tool unavailable');
@@ -197,4 +229,5 @@ export function createProtectedMCPHandler(options) {
197
229
  res.destroy();
198
230
  }
199
231
  };
232
+ return Object.assign(handle, { flush: async () => { await catalogReporter?.flush(); } });
200
233
  }
package/package.json CHANGED
@@ -10,7 +10,7 @@
10
10
  "check:package": "node scripts/check-package.mjs",
11
11
  "test:types": "tsc --strict --noEmit --module nodenext --target es2022 test/types.mts test/mcp-types.mts"
12
12
  },
13
- "version": "0.1.0-alpha.6",
13
+ "version": "0.1.0-alpha.7",
14
14
  "exports": {
15
15
  "./fetch": {
16
16
  "types": "./fetch.d.mts",