@mcpfn/datafn 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.
package/README.md ADDED
@@ -0,0 +1,55 @@
1
+ # McpFn DataFn Adapter
2
+
3
+ `@mcpfn/datafn` turns explicitly approved DataFn operations into stable MCP tools. It is deny-by-default:
4
+
5
+ - no resource is exposed unless named in `expose`;
6
+ - every read uses a fixed output projection;
7
+ - filters and sort fields are allowlisted;
8
+ - writes require explicit writable fields and a caller-supplied idempotency key;
9
+ - principal and namespace context comes from the server, never tool arguments;
10
+ - all calls execute through `DatafnExecutor`, preserving DataFn validation, permissions, hooks, authorization, namespace isolation, rate limits, and idempotency.
11
+
12
+ ```ts
13
+ import { createMcpFnServer } from "@mcpfn/core";
14
+ import { createDatafnMcpRegistry } from "@mcpfn/datafn";
15
+
16
+ const registry = createDatafnMcpRegistry({
17
+ schema,
18
+ executor: datafnServer.executor,
19
+ context: (mcpContext) => ({
20
+ workspaceId: mcpContext.workspaceId,
21
+ actorId: mcpContext.actorId,
22
+ }),
23
+ clientId: (mcpContext) => `mcp:${mcpContext.credentialId}`,
24
+ expose: {
25
+ skills: {
26
+ fields: ["id", "slug", "name", "updatedAt"],
27
+ list: {
28
+ filterFields: ["slug", "name"],
29
+ sortFields: ["updatedAt", "id"],
30
+ maxLimit: 50,
31
+ },
32
+ get: true,
33
+ },
34
+ },
35
+ });
36
+
37
+ const server = createMcpFnServer({
38
+ info: { name: "skills-data", version: "1.0.0" },
39
+ registry,
40
+ context: async (extra) => authenticateMcpRequest(extra.requestInfo),
41
+ transports: ["stdio", "streamable-http"],
42
+ });
43
+ ```
44
+
45
+ This adapter is appropriate for bounded data operations. Domain workflows with additional authorization, auditing, asset grants, or version-resolution semantics should remain explicit McpFn tools.
46
+
47
+ ## Exposure reference
48
+
49
+ - `fields` is the fixed list/get projection and must be non-empty, unique, and allowed by DataFn read policy.
50
+ - `list` and `get` default to enabled after the resource itself is explicitly present in `expose`; pass `false` to disable either one.
51
+ - `list.filterFields` defaults to `fields`; `sortFields` defaults to `id`; `defaultLimit` defaults to `50`; `maxLimit` defaults to `100`.
52
+ - `create`, `update`, and `delete` default off. Create/update require a writable `fields` allowlist. All writes require `mutationId` and use the trusted `clientId` resolver.
53
+ - Default names are `datafn_<resource>_<operation>`; `toolPrefix`, per-operation `name`, and descriptions can be overridden.
54
+
55
+ Adapter construction fails before serving if a resource or field is unknown, unreadable, read-only, or not writable under the resolved DataFn capabilities.
package/dist/index.cjs ADDED
@@ -0,0 +1,475 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var index_exports = {};
22
+ __export(index_exports, {
23
+ createDatafnMcpRegistry: () => createDatafnMcpRegistry
24
+ });
25
+ module.exports = __toCommonJS(index_exports);
26
+
27
+ // src/adapter.ts
28
+ var import_core = require("@datafn/core");
29
+ var import_core2 = require("@mcpfn/core");
30
+ function validateFieldList(label, fields) {
31
+ if (fields.length === 0 || new Set(fields).size !== fields.length || fields.some((field) => typeof field !== "string" || !field)) {
32
+ throw new import_core2.McpFnValidationError(`${label} must be a non-empty, unique field list`);
33
+ }
34
+ }
35
+ function validateLimit(label, value) {
36
+ if (!Number.isSafeInteger(value) || value < 1) {
37
+ throw new import_core2.McpFnValidationError(`${label} must be a positive safe integer`);
38
+ }
39
+ }
40
+ async function resolveClientId(options, context) {
41
+ const clientId = typeof options.clientId === "string" ? options.clientId : await options.clientId(context);
42
+ if (typeof clientId !== "string" || !clientId.trim()) {
43
+ throw new import_core2.McpFnValidationError("DataFn clientId must resolve to a non-empty string");
44
+ }
45
+ return clientId;
46
+ }
47
+ function safeSegment(value) {
48
+ let segment = "";
49
+ let needsSeparator = false;
50
+ for (const character of value) {
51
+ const code = character.charCodeAt(0);
52
+ const allowed = code >= 48 && code <= 57 || code >= 65 && code <= 90 || code >= 97 && code <= 122 || character === "_" || character === "." || character === "-";
53
+ if (allowed) {
54
+ if (needsSeparator && segment) segment += "_";
55
+ segment += character;
56
+ needsSeparator = false;
57
+ } else {
58
+ needsSeparator = true;
59
+ }
60
+ }
61
+ let start = 0;
62
+ let end = segment.length;
63
+ while (start < end && segment[start] === "_") start += 1;
64
+ while (end > start && segment[end - 1] === "_") end -= 1;
65
+ return segment.slice(start, end);
66
+ }
67
+ function resourceDefaults(schema, resource) {
68
+ if (resource.permissions !== void 0 || resource.defaultPermissions === false) {
69
+ return void 0;
70
+ }
71
+ return schema.defaultPermissions;
72
+ }
73
+ function fieldSchema(field) {
74
+ const base = (() => {
75
+ switch (field.type) {
76
+ case "number":
77
+ return { type: "number" };
78
+ case "boolean":
79
+ return { type: "boolean" };
80
+ case "array":
81
+ return { type: "array", items: {} };
82
+ case "object":
83
+ return { type: "object", additionalProperties: true };
84
+ case "json":
85
+ return { type: ["string", "number", "boolean", "object", "array"] };
86
+ case "date":
87
+ return { type: ["string", "number"], format: "date-time" };
88
+ case "file":
89
+ return { type: "string" };
90
+ default:
91
+ return { type: "string" };
92
+ }
93
+ })();
94
+ if (field.enum) base.enum = field.enum;
95
+ if (field.min !== void 0) base.minimum = field.min;
96
+ if (field.max !== void 0) base.maximum = field.max;
97
+ if (field.minLength !== void 0) base.minLength = field.minLength;
98
+ if (field.maxLength !== void 0) base.maxLength = field.maxLength;
99
+ if (field.pattern !== void 0) base.pattern = field.pattern;
100
+ if (field.nullable) {
101
+ const currentTypes = Array.isArray(base.type) ? base.type : [base.type];
102
+ base.type = [.../* @__PURE__ */ new Set([...currentTypes, "null"])];
103
+ if (Array.isArray(base.enum) && !base.enum.includes(null)) {
104
+ base.enum = [...base.enum, null];
105
+ }
106
+ }
107
+ return base;
108
+ }
109
+ function capabilitiesFor(schema, resource) {
110
+ return (0, import_core.getCapabilityFields)(
111
+ (0, import_core.resolveCapabilities)(schema.capabilities, resource.capabilities)
112
+ );
113
+ }
114
+ function fieldMaps(schema, resource) {
115
+ const schemaFields = new Map(resource.fields.map((field) => [field.name, field]));
116
+ for (const field of capabilitiesFor(schema, resource)) {
117
+ schemaFields.set(field.name, field);
118
+ }
119
+ const defaults = resourceDefaults(schema, resource);
120
+ const readDefault = typeof defaults === "string" ? defaults : defaults?.read;
121
+ const writeDefault = typeof defaults === "string" ? defaults : defaults?.write;
122
+ const defaultFields = ["id", ...resource.fields.map((field) => field.name)];
123
+ const readable = /* @__PURE__ */ new Set([
124
+ "id",
125
+ ...resource.permissions?.read?.fields ?? (readDefault === "allResourceFields" ? defaultFields : [])
126
+ ]);
127
+ for (const field of capabilitiesFor(schema, resource)) readable.add(field.name);
128
+ const writable = new Set(
129
+ resource.permissions?.write?.fields ?? (writeDefault === "allResourceFields" ? defaultFields : [])
130
+ );
131
+ return { schemaFields, readable, writable };
132
+ }
133
+ function validateReadFields(schema, resource, fields) {
134
+ const defaults = resourceDefaults(schema, resource);
135
+ const readDefault = typeof defaults === "string" ? defaults : defaults?.read;
136
+ if (!resource.permissions?.read && readDefault !== "allResourceFields") {
137
+ throw new import_core2.McpFnValidationError(
138
+ `DataFn resource ${resource.name} has no read policy and cannot be exposed`
139
+ );
140
+ }
141
+ const { schemaFields, readable } = fieldMaps(schema, resource);
142
+ for (const field of fields) {
143
+ if (field !== "id" && !schemaFields.has(field)) {
144
+ throw new import_core2.McpFnValidationError(
145
+ `Unknown exposed field ${resource.name}.${field}`
146
+ );
147
+ }
148
+ if (!readable.has(field)) {
149
+ throw new import_core2.McpFnValidationError(
150
+ `Field ${resource.name}.${field} is not readable by DataFn policy`
151
+ );
152
+ }
153
+ }
154
+ }
155
+ function validateWriteFields(schema, resource, fields) {
156
+ const defaults = resourceDefaults(schema, resource);
157
+ const writeDefault = typeof defaults === "string" ? defaults : defaults?.write;
158
+ if (!resource.permissions?.write && writeDefault !== "allResourceFields") {
159
+ throw new import_core2.McpFnValidationError(
160
+ `DataFn resource ${resource.name} has no write policy and cannot expose mutations`
161
+ );
162
+ }
163
+ const { schemaFields, writable } = fieldMaps(schema, resource);
164
+ for (const field of fields) {
165
+ const definition = schemaFields.get(field);
166
+ if (!definition) {
167
+ throw new import_core2.McpFnValidationError(`Unknown write field ${resource.name}.${field}`);
168
+ }
169
+ if (definition.readonly || !writable.has(field)) {
170
+ throw new import_core2.McpFnValidationError(
171
+ `Field ${resource.name}.${field} is not writable by DataFn policy`
172
+ );
173
+ }
174
+ }
175
+ }
176
+ function operationOptions(value, enabledByDefault) {
177
+ if (value === false) return void 0;
178
+ if (value === true) return {};
179
+ if (value === void 0) return enabledByDefault ? {} : void 0;
180
+ return value;
181
+ }
182
+ function outputSchema() {
183
+ return {
184
+ type: "object",
185
+ properties: {
186
+ resource: { type: "string" },
187
+ operation: { type: "string" },
188
+ result: {}
189
+ },
190
+ required: ["resource", "operation", "result"],
191
+ additionalProperties: false
192
+ };
193
+ }
194
+ function defaultName(prefix, resource, operation) {
195
+ return [prefix, safeSegment(resource), operation].filter(Boolean).join("_");
196
+ }
197
+ function assertUniqueToolNames(registry, expose, prefix) {
198
+ const owners = /* @__PURE__ */ new Map();
199
+ for (const resourceName of Object.keys(expose).sort()) {
200
+ const exposure = expose[resourceName];
201
+ const operations = [
202
+ ["list", operationOptions(exposure.list, true)],
203
+ ["get", operationOptions(exposure.get, true)],
204
+ ["create", exposure.create || void 0],
205
+ ["update", exposure.update || void 0],
206
+ ["delete", operationOptions(exposure.delete, false)]
207
+ ];
208
+ for (const [operation, config] of operations) {
209
+ if (!config) continue;
210
+ const name = config.name ?? defaultName(prefix, resourceName, operation);
211
+ const owner = `${resourceName}.${operation}`;
212
+ const existing = owners.get(name);
213
+ if (existing || registry.has(name)) {
214
+ throw new import_core2.McpFnValidationError(
215
+ `DataFn tool name collision for ${name}: ${existing ?? "existing registry tool"} and ${owner}`
216
+ );
217
+ }
218
+ owners.set(name, owner);
219
+ }
220
+ }
221
+ }
222
+ function createDatafnMcpRegistry(options) {
223
+ const registry = options.registry ?? new import_core2.McpFnRegistry();
224
+ const schema = options.executor.schema;
225
+ const prefix = safeSegment(options.toolPrefix ?? "datafn");
226
+ if (typeof options.clientId === "string" && !options.clientId.trim()) {
227
+ throw new import_core2.McpFnValidationError("DataFn clientId must be a non-empty string");
228
+ }
229
+ assertUniqueToolNames(registry, options.expose, prefix);
230
+ for (const resourceName of Object.keys(options.expose).sort()) {
231
+ const exposure = options.expose[resourceName];
232
+ const resource = schema.resources.find((candidate) => candidate.name === resourceName);
233
+ if (!resource) {
234
+ throw new import_core2.McpFnValidationError(`Unknown DataFn resource: ${resourceName}`);
235
+ }
236
+ const list = operationOptions(exposure.list, true);
237
+ const get = operationOptions(exposure.get, true);
238
+ validateFieldList(`DataFn resource ${resourceName} projection`, exposure.fields);
239
+ if (list || get) validateReadFields(schema, resource, exposure.fields);
240
+ const maps = fieldMaps(schema, resource);
241
+ if (list) {
242
+ const filterFields = list.filterFields ?? exposure.fields;
243
+ const sortFields = list.sortFields ?? ["id"];
244
+ validateFieldList(`DataFn resource ${resourceName} filterFields`, filterFields);
245
+ validateFieldList(`DataFn resource ${resourceName} sortFields`, sortFields);
246
+ validateReadFields(schema, resource, [...filterFields, ...sortFields]);
247
+ const filterProperties = Object.fromEntries(
248
+ filterFields.map((field) => [
249
+ field,
250
+ field === "id" ? { type: "string" } : fieldSchema(maps.schemaFields.get(field))
251
+ ])
252
+ );
253
+ const maxLimit = list.maxLimit ?? 100;
254
+ validateLimit(`DataFn resource ${resourceName} maxLimit`, maxLimit);
255
+ const defaultLimit = list.defaultLimit ?? Math.min(50, maxLimit);
256
+ validateLimit(`DataFn resource ${resourceName} defaultLimit`, defaultLimit);
257
+ if (defaultLimit > maxLimit) {
258
+ throw new import_core2.McpFnValidationError(
259
+ `DataFn resource ${resourceName} defaultLimit cannot exceed maxLimit`
260
+ );
261
+ }
262
+ const definition = {
263
+ name: list.name ?? defaultName(prefix, resourceName, "list"),
264
+ description: list.description ?? `List ${resourceName} records visible to the authenticated DataFn context.`,
265
+ inputSchema: {
266
+ type: "object",
267
+ properties: {
268
+ filters: {
269
+ type: "object",
270
+ properties: filterProperties,
271
+ additionalProperties: false
272
+ },
273
+ sort: {
274
+ type: "array",
275
+ items: {
276
+ type: "string",
277
+ enum: sortFields.flatMap((field) => [`${field}:asc`, `${field}:desc`])
278
+ },
279
+ maxItems: Math.max(1, sortFields.length)
280
+ },
281
+ cursor: { type: "object", additionalProperties: true },
282
+ limit: { type: "integer", minimum: 1, maximum: maxLimit }
283
+ },
284
+ additionalProperties: false
285
+ },
286
+ outputSchema: outputSchema(),
287
+ annotations: {
288
+ readOnlyHint: true,
289
+ destructiveHint: false,
290
+ idempotentHint: true,
291
+ openWorldHint: false
292
+ },
293
+ metadata: { "mcpfn/datafn": { resource: resourceName, operation: "list" } },
294
+ handler: async (args, context) => {
295
+ const requestedSort = args.sort;
296
+ const querySort = requestedSort?.length ? [
297
+ ...requestedSort.filter((term) => !term.startsWith("id:")),
298
+ requestedSort.find((term) => term.startsWith("id:")) ?? "id:asc"
299
+ ] : void 0;
300
+ const result = await options.executor.query(
301
+ {
302
+ resource: resourceName,
303
+ version: String(resource.version),
304
+ select: exposure.fields,
305
+ ...args.filters ? { filters: args.filters } : {},
306
+ ...querySort ? { sort: querySort } : {},
307
+ ...args.cursor ? { cursor: args.cursor } : {},
308
+ limit: Math.min(Number(args.limit ?? defaultLimit), maxLimit)
309
+ },
310
+ await options.context(context)
311
+ );
312
+ return (0, import_core2.structuredResult)({ resource: resourceName, operation: "list", result });
313
+ }
314
+ };
315
+ registry.register(definition);
316
+ }
317
+ if (get) {
318
+ registry.register({
319
+ name: get.name ?? defaultName(prefix, resourceName, "get"),
320
+ description: get.description ?? `Get one ${resourceName} record by ID.`,
321
+ inputSchema: {
322
+ type: "object",
323
+ properties: { id: { type: "string", minLength: 1 } },
324
+ required: ["id"],
325
+ additionalProperties: false
326
+ },
327
+ outputSchema: outputSchema(),
328
+ annotations: {
329
+ readOnlyHint: true,
330
+ destructiveHint: false,
331
+ idempotentHint: true,
332
+ openWorldHint: false
333
+ },
334
+ metadata: { "mcpfn/datafn": { resource: resourceName, operation: "get" } },
335
+ handler: async ({ id }, context) => {
336
+ const result = await options.executor.query(
337
+ {
338
+ resource: resourceName,
339
+ version: String(resource.version),
340
+ select: exposure.fields,
341
+ filters: { id },
342
+ limit: 1
343
+ },
344
+ await options.context(context)
345
+ );
346
+ return (0, import_core2.structuredResult)({ resource: resourceName, operation: "get", result });
347
+ }
348
+ });
349
+ }
350
+ const registerWrite = (operation, config) => {
351
+ validateFieldList(
352
+ `DataFn resource ${resourceName} ${operation} fields`,
353
+ config.fields
354
+ );
355
+ validateWriteFields(schema, resource, config.fields);
356
+ const requiredCreateFields = [...maps.schemaFields.values()].filter((field) => field.name !== "id" && field.required && field.default === void 0 && !field.readonly).map((field) => field.name).sort();
357
+ if (operation === "create") {
358
+ const missingRequiredFields = requiredCreateFields.filter(
359
+ (field) => !config.fields.includes(field)
360
+ );
361
+ if (missingRequiredFields.length) {
362
+ throw new import_core2.McpFnValidationError(
363
+ `DataFn resource ${resourceName} create fields omit required writable fields: ${missingRequiredFields.join(", ")}`
364
+ );
365
+ }
366
+ }
367
+ const properties = Object.fromEntries(
368
+ config.fields.map((field) => [field, fieldSchema(maps.schemaFields.get(field))])
369
+ );
370
+ const recordRequired = operation === "create" ? requiredCreateFields : [];
371
+ registry.register({
372
+ name: config.name ?? defaultName(prefix, resourceName, operation),
373
+ description: config.description ?? `${operation === "create" ? "Create" : "Update"} one ${resourceName} record.`,
374
+ inputSchema: {
375
+ type: "object",
376
+ properties: {
377
+ ...operation === "create" ? { id: { type: "string", minLength: 1 } } : {},
378
+ ...operation === "update" ? { id: { type: "string", minLength: 1 } } : {},
379
+ mutationId: { type: "string", minLength: 1 },
380
+ record: {
381
+ type: "object",
382
+ properties,
383
+ ...recordRequired.length ? { required: recordRequired } : {},
384
+ additionalProperties: false
385
+ }
386
+ },
387
+ required: ["mutationId", "record", ...operation === "update" ? ["id"] : []],
388
+ additionalProperties: false
389
+ },
390
+ outputSchema: outputSchema(),
391
+ annotations: {
392
+ readOnlyHint: false,
393
+ destructiveHint: false,
394
+ idempotentHint: true,
395
+ openWorldHint: false
396
+ },
397
+ metadata: { "mcpfn/datafn": { resource: resourceName, operation } },
398
+ handler: async (args, context) => {
399
+ const clientId = await resolveClientId(options, context);
400
+ const result = await options.executor.mutate(
401
+ {
402
+ resource: resourceName,
403
+ version: String(resource.version),
404
+ operation: operation === "create" ? "insert" : "merge",
405
+ clientId,
406
+ mutationId: args.mutationId,
407
+ ...args.id ? { id: args.id } : {},
408
+ record: args.record
409
+ },
410
+ await options.context(context)
411
+ );
412
+ return (0, import_core2.structuredResult)({ resource: resourceName, operation, result });
413
+ }
414
+ });
415
+ };
416
+ if (exposure.create) registerWrite("create", exposure.create);
417
+ if (exposure.update) registerWrite("update", exposure.update);
418
+ const remove = operationOptions(
419
+ exposure.delete,
420
+ false
421
+ );
422
+ if (remove) {
423
+ const config = remove;
424
+ const defaults = resourceDefaults(schema, resource);
425
+ const writeDefault = typeof defaults === "string" ? defaults : defaults?.write;
426
+ if (!resource.permissions?.write && writeDefault !== "allResourceFields") {
427
+ throw new import_core2.McpFnValidationError(
428
+ `DataFn resource ${resourceName} has no write policy and cannot expose delete`
429
+ );
430
+ }
431
+ registry.register({
432
+ name: config.name ?? defaultName(prefix, resourceName, "delete"),
433
+ description: config.description ?? `Delete one ${resourceName} record by ID.`,
434
+ inputSchema: {
435
+ type: "object",
436
+ properties: {
437
+ id: { type: "string", minLength: 1 },
438
+ mutationId: { type: "string", minLength: 1 }
439
+ },
440
+ required: ["id", "mutationId"],
441
+ additionalProperties: false
442
+ },
443
+ outputSchema: outputSchema(),
444
+ annotations: {
445
+ readOnlyHint: false,
446
+ destructiveHint: true,
447
+ idempotentHint: true,
448
+ openWorldHint: false
449
+ },
450
+ metadata: { "mcpfn/datafn": { resource: resourceName, operation: "delete" } },
451
+ handler: async ({ id, mutationId }, context) => {
452
+ const clientId = await resolveClientId(options, context);
453
+ const result = await options.executor.mutate(
454
+ {
455
+ resource: resourceName,
456
+ version: String(resource.version),
457
+ operation: "delete",
458
+ clientId,
459
+ mutationId,
460
+ id
461
+ },
462
+ await options.context(context)
463
+ );
464
+ return (0, import_core2.structuredResult)({ resource: resourceName, operation: "delete", result });
465
+ }
466
+ });
467
+ }
468
+ }
469
+ return registry;
470
+ }
471
+ // Annotate the CommonJS export names for ESM import in node:
472
+ 0 && (module.exports = {
473
+ createDatafnMcpRegistry
474
+ });
475
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.ts","../src/adapter.ts"],"sourcesContent":["export * from \"./adapter.js\";\nexport * from \"./types.js\";\n","import {\n getCapabilityFields,\n resolveCapabilities,\n type DatafnFieldSchema,\n type DatafnResourceSchema,\n type DatafnSchema,\n} from \"@datafn/core\";\nimport {\n McpFnRegistry,\n McpFnValidationError,\n structuredResult,\n type McpFnJsonSchema,\n type McpFnToolDefinition,\n} from \"@mcpfn/core\";\n\nimport type {\n CreateDatafnMcpRegistryOptions,\n DatafnListToolOptions,\n DatafnReadToolOptions,\n DatafnResourceExposure,\n DatafnWriteToolOptions,\n} from \"./types.js\";\n\ntype Operation = \"list\" | \"get\" | \"create\" | \"update\" | \"delete\";\n\nfunction validateFieldList(label: string, fields: string[]): void {\n if (\n fields.length === 0 ||\n new Set(fields).size !== fields.length ||\n fields.some((field) => typeof field !== \"string\" || !field)\n ) {\n throw new McpFnValidationError(`${label} must be a non-empty, unique field list`);\n }\n}\n\nfunction validateLimit(label: string, value: number): void {\n if (!Number.isSafeInteger(value) || value < 1) {\n throw new McpFnValidationError(`${label} must be a positive safe integer`);\n }\n}\n\nasync function resolveClientId<TMcpContext, TDatafnContext>(\n options: CreateDatafnMcpRegistryOptions<TMcpContext, TDatafnContext>,\n context: TMcpContext,\n): Promise<string> {\n const clientId = typeof options.clientId === \"string\"\n ? options.clientId\n : await options.clientId(context);\n if (typeof clientId !== \"string\" || !clientId.trim()) {\n throw new McpFnValidationError(\"DataFn clientId must resolve to a non-empty string\");\n }\n return clientId;\n}\n\nfunction safeSegment(value: string): string {\n let segment = \"\";\n let needsSeparator = false;\n for (const character of value) {\n const code = character.charCodeAt(0);\n const allowed =\n (code >= 48 && code <= 57) ||\n (code >= 65 && code <= 90) ||\n (code >= 97 && code <= 122) ||\n character === \"_\" || character === \".\" || character === \"-\";\n if (allowed) {\n if (needsSeparator && segment) segment += \"_\";\n segment += character;\n needsSeparator = false;\n } else {\n needsSeparator = true;\n }\n }\n let start = 0;\n let end = segment.length;\n while (start < end && segment[start] === \"_\") start += 1;\n while (end > start && segment[end - 1] === \"_\") end -= 1;\n return segment.slice(start, end);\n}\n\nfunction resourceDefaults(\n schema: DatafnSchema,\n resource: DatafnResourceSchema,\n) {\n if (resource.permissions !== undefined || resource.defaultPermissions === false) {\n return undefined;\n }\n return schema.defaultPermissions;\n}\n\nfunction fieldSchema(field: DatafnFieldSchema): McpFnJsonSchema {\n const base: McpFnJsonSchema = (() => {\n switch (field.type) {\n case \"number\": return { type: \"number\" };\n case \"boolean\": return { type: \"boolean\" };\n case \"array\": return { type: \"array\", items: {} };\n case \"object\": return { type: \"object\", additionalProperties: true };\n case \"json\": return { type: [\"string\", \"number\", \"boolean\", \"object\", \"array\"] };\n case \"date\": return { type: [\"string\", \"number\"], format: \"date-time\" };\n case \"file\": return { type: \"string\" };\n default: return { type: \"string\" };\n }\n })();\n if (field.enum) base.enum = field.enum;\n if (field.min !== undefined) base.minimum = field.min;\n if (field.max !== undefined) base.maximum = field.max;\n if (field.minLength !== undefined) base.minLength = field.minLength;\n if (field.maxLength !== undefined) base.maxLength = field.maxLength;\n if (field.pattern !== undefined) base.pattern = field.pattern;\n if (field.nullable) {\n const currentTypes = Array.isArray(base.type) ? base.type : [base.type];\n base.type = [...new Set([...currentTypes, \"null\"])];\n if (Array.isArray(base.enum) && !base.enum.includes(null)) {\n base.enum = [...base.enum, null];\n }\n }\n return base;\n}\n\nfunction capabilitiesFor(\n schema: DatafnSchema,\n resource: DatafnResourceSchema,\n) {\n return getCapabilityFields(\n resolveCapabilities(schema.capabilities as never, resource.capabilities as never) as never,\n );\n}\n\nfunction fieldMaps(\n schema: DatafnSchema,\n resource: DatafnResourceSchema,\n) {\n const schemaFields = new Map(resource.fields.map((field) => [field.name, field]));\n for (const field of capabilitiesFor(schema, resource)) {\n schemaFields.set(field.name, field as DatafnFieldSchema);\n }\n const defaults = resourceDefaults(schema, resource);\n const readDefault = typeof defaults === \"string\" ? defaults : defaults?.read;\n const writeDefault = typeof defaults === \"string\" ? defaults : defaults?.write;\n const defaultFields = [\"id\", ...resource.fields.map((field) => field.name)];\n const readable = new Set([\n \"id\",\n ...(resource.permissions?.read?.fields ??\n (readDefault === \"allResourceFields\" ? defaultFields : [])),\n ]);\n for (const field of capabilitiesFor(schema, resource)) readable.add(field.name);\n const writable = new Set(\n resource.permissions?.write?.fields ??\n (writeDefault === \"allResourceFields\" ? defaultFields : []),\n );\n return { schemaFields, readable, writable };\n}\n\nfunction validateReadFields(\n schema: DatafnSchema,\n resource: DatafnResourceSchema,\n fields: string[],\n): void {\n const defaults = resourceDefaults(schema, resource);\n const readDefault = typeof defaults === \"string\" ? defaults : defaults?.read;\n if (!resource.permissions?.read && readDefault !== \"allResourceFields\") {\n throw new McpFnValidationError(\n `DataFn resource ${resource.name} has no read policy and cannot be exposed`,\n );\n }\n const { schemaFields, readable } = fieldMaps(schema, resource);\n for (const field of fields) {\n if (field !== \"id\" && !schemaFields.has(field)) {\n throw new McpFnValidationError(\n `Unknown exposed field ${resource.name}.${field}`,\n );\n }\n if (!readable.has(field)) {\n throw new McpFnValidationError(\n `Field ${resource.name}.${field} is not readable by DataFn policy`,\n );\n }\n }\n}\n\nfunction validateWriteFields(\n schema: DatafnSchema,\n resource: DatafnResourceSchema,\n fields: string[],\n): void {\n const defaults = resourceDefaults(schema, resource);\n const writeDefault = typeof defaults === \"string\" ? defaults : defaults?.write;\n if (!resource.permissions?.write && writeDefault !== \"allResourceFields\") {\n throw new McpFnValidationError(\n `DataFn resource ${resource.name} has no write policy and cannot expose mutations`,\n );\n }\n const { schemaFields, writable } = fieldMaps(schema, resource);\n for (const field of fields) {\n const definition = schemaFields.get(field);\n if (!definition) {\n throw new McpFnValidationError(`Unknown write field ${resource.name}.${field}`);\n }\n if (definition.readonly || !writable.has(field)) {\n throw new McpFnValidationError(\n `Field ${resource.name}.${field} is not writable by DataFn policy`,\n );\n }\n }\n}\n\nfunction operationOptions<T>(value: boolean | T | undefined, enabledByDefault: boolean): T | undefined {\n if (value === false) return undefined;\n if (value === true) return {} as T;\n if (value === undefined) return enabledByDefault ? ({} as T) : undefined;\n return value;\n}\n\nfunction outputSchema() {\n return {\n type: \"object\" as const,\n properties: {\n resource: { type: \"string\" },\n operation: { type: \"string\" },\n result: {},\n },\n required: [\"resource\", \"operation\", \"result\"],\n additionalProperties: false,\n };\n}\n\nfunction defaultName(prefix: string, resource: string, operation: Operation): string {\n return [prefix, safeSegment(resource), operation].filter(Boolean).join(\"_\");\n}\n\nfunction assertUniqueToolNames<TMcpContext>(\n registry: McpFnRegistry<TMcpContext>,\n expose: Record<string, DatafnResourceExposure>,\n prefix: string,\n): void {\n const owners = new Map<string, string>();\n for (const resourceName of Object.keys(expose).sort()) {\n const exposure = expose[resourceName]!;\n const operations: Array<[Operation, DatafnReadToolOptions | DatafnWriteToolOptions | undefined]> = [\n [\"list\", operationOptions<DatafnListToolOptions>(exposure.list, true)],\n [\"get\", operationOptions<DatafnReadToolOptions>(exposure.get, true)],\n [\"create\", exposure.create || undefined],\n [\"update\", exposure.update || undefined],\n [\"delete\", operationOptions<Omit<DatafnWriteToolOptions, \"fields\">>(exposure.delete, false)],\n ];\n for (const [operation, config] of operations) {\n if (!config) continue;\n const name = config.name ?? defaultName(prefix, resourceName, operation);\n const owner = `${resourceName}.${operation}`;\n const existing = owners.get(name);\n if (existing || registry.has(name)) {\n throw new McpFnValidationError(\n `DataFn tool name collision for ${name}: ${existing ?? \"existing registry tool\"} and ${owner}`,\n );\n }\n owners.set(name, owner);\n }\n }\n}\n\nexport function createDatafnMcpRegistry<TMcpContext, TDatafnContext>(\n options: CreateDatafnMcpRegistryOptions<TMcpContext, TDatafnContext>,\n): McpFnRegistry<TMcpContext> {\n const registry = options.registry ?? new McpFnRegistry<TMcpContext>();\n const schema = options.executor.schema;\n const prefix = safeSegment(options.toolPrefix ?? \"datafn\");\n if (typeof options.clientId === \"string\" && !options.clientId.trim()) {\n throw new McpFnValidationError(\"DataFn clientId must be a non-empty string\");\n }\n assertUniqueToolNames(registry, options.expose, prefix);\n\n for (const resourceName of Object.keys(options.expose).sort()) {\n const exposure = options.expose[resourceName]!;\n const resource = schema.resources.find((candidate) => candidate.name === resourceName);\n if (!resource) {\n throw new McpFnValidationError(`Unknown DataFn resource: ${resourceName}`);\n }\n const list = operationOptions<DatafnListToolOptions>(exposure.list, true);\n const get = operationOptions<DatafnReadToolOptions>(exposure.get, true);\n validateFieldList(`DataFn resource ${resourceName} projection`, exposure.fields);\n if (list || get) validateReadFields(schema, resource, exposure.fields);\n const maps = fieldMaps(schema, resource);\n\n if (list) {\n const filterFields = list.filterFields ?? exposure.fields;\n const sortFields = list.sortFields ?? [\"id\"];\n validateFieldList(`DataFn resource ${resourceName} filterFields`, filterFields);\n validateFieldList(`DataFn resource ${resourceName} sortFields`, sortFields);\n validateReadFields(schema, resource, [...filterFields, ...sortFields]);\n const filterProperties = Object.fromEntries(\n filterFields.map((field) => [\n field,\n field === \"id\" ? { type: \"string\" } : fieldSchema(maps.schemaFields.get(field)!),\n ]),\n );\n const maxLimit = list.maxLimit ?? 100;\n validateLimit(`DataFn resource ${resourceName} maxLimit`, maxLimit);\n const defaultLimit = list.defaultLimit ?? Math.min(50, maxLimit);\n validateLimit(`DataFn resource ${resourceName} defaultLimit`, defaultLimit);\n if (defaultLimit > maxLimit) {\n throw new McpFnValidationError(\n `DataFn resource ${resourceName} defaultLimit cannot exceed maxLimit`,\n );\n }\n const definition: McpFnToolDefinition<TMcpContext> = {\n name: list.name ?? defaultName(prefix, resourceName, \"list\"),\n description:\n list.description ?? `List ${resourceName} records visible to the authenticated DataFn context.`,\n inputSchema: {\n type: \"object\",\n properties: {\n filters: {\n type: \"object\",\n properties: filterProperties,\n additionalProperties: false,\n },\n sort: {\n type: \"array\",\n items: {\n type: \"string\",\n enum: sortFields.flatMap((field) => [`${field}:asc`, `${field}:desc`]),\n },\n maxItems: Math.max(1, sortFields.length),\n },\n cursor: { type: \"object\", additionalProperties: true },\n limit: { type: \"integer\", minimum: 1, maximum: maxLimit },\n },\n additionalProperties: false,\n },\n outputSchema: outputSchema(),\n annotations: {\n readOnlyHint: true,\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: false,\n },\n metadata: { \"mcpfn/datafn\": { resource: resourceName, operation: \"list\" } },\n handler: async (args, context) => {\n const requestedSort = args.sort as string[] | undefined;\n const querySort = requestedSort?.length\n ? [\n ...requestedSort.filter((term) => !term.startsWith(\"id:\")),\n requestedSort.find((term) => term.startsWith(\"id:\")) ?? \"id:asc\",\n ]\n : undefined;\n const result = await options.executor.query(\n {\n resource: resourceName,\n version: String(resource.version),\n select: exposure.fields,\n ...(args.filters ? { filters: args.filters } : {}),\n ...(querySort ? { sort: querySort } : {}),\n ...(args.cursor ? { cursor: args.cursor } : {}),\n limit: Math.min(Number(args.limit ?? defaultLimit), maxLimit),\n },\n await options.context(context),\n );\n return structuredResult({ resource: resourceName, operation: \"list\", result });\n },\n };\n registry.register(definition);\n }\n\n if (get) {\n registry.register({\n name: get.name ?? defaultName(prefix, resourceName, \"get\"),\n description: get.description ?? `Get one ${resourceName} record by ID.`,\n inputSchema: {\n type: \"object\",\n properties: { id: { type: \"string\", minLength: 1 } },\n required: [\"id\"],\n additionalProperties: false,\n },\n outputSchema: outputSchema(),\n annotations: {\n readOnlyHint: true,\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: false,\n },\n metadata: { \"mcpfn/datafn\": { resource: resourceName, operation: \"get\" } },\n handler: async ({ id }, context) => {\n const result = await options.executor.query(\n {\n resource: resourceName,\n version: String(resource.version),\n select: exposure.fields,\n filters: { id },\n limit: 1,\n },\n await options.context(context),\n );\n return structuredResult({ resource: resourceName, operation: \"get\", result });\n },\n });\n }\n\n const registerWrite = (\n operation: \"create\" | \"update\",\n config: DatafnWriteToolOptions,\n ) => {\n validateFieldList(\n `DataFn resource ${resourceName} ${operation} fields`,\n config.fields,\n );\n validateWriteFields(schema, resource, config.fields);\n const requiredCreateFields = [...maps.schemaFields.values()]\n .filter((field) =>\n field.name !== \"id\" &&\n field.required &&\n field.default === undefined &&\n !field.readonly)\n .map((field) => field.name)\n .sort();\n if (operation === \"create\") {\n const missingRequiredFields = requiredCreateFields.filter(\n (field) => !config.fields.includes(field),\n );\n if (missingRequiredFields.length) {\n throw new McpFnValidationError(\n `DataFn resource ${resourceName} create fields omit required writable fields: ${missingRequiredFields.join(\", \")}`,\n );\n }\n }\n const properties = Object.fromEntries(\n config.fields.map((field) => [field, fieldSchema(maps.schemaFields.get(field)!)]),\n );\n const recordRequired = operation === \"create\"\n ? requiredCreateFields\n : [];\n registry.register({\n name: config.name ?? defaultName(prefix, resourceName, operation),\n description: config.description ?? `${operation === \"create\" ? \"Create\" : \"Update\"} one ${resourceName} record.`,\n inputSchema: {\n type: \"object\",\n properties: {\n ...(operation === \"create\" ? { id: { type: \"string\", minLength: 1 } } : {}),\n ...(operation === \"update\" ? { id: { type: \"string\", minLength: 1 } } : {}),\n mutationId: { type: \"string\", minLength: 1 },\n record: {\n type: \"object\",\n properties,\n ...(recordRequired.length ? { required: recordRequired } : {}),\n additionalProperties: false,\n },\n },\n required: [\"mutationId\", \"record\", ...(operation === \"update\" ? [\"id\"] : [])],\n additionalProperties: false,\n },\n outputSchema: outputSchema(),\n annotations: {\n readOnlyHint: false,\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: false,\n },\n metadata: { \"mcpfn/datafn\": { resource: resourceName, operation } },\n handler: async (args, context) => {\n const clientId = await resolveClientId(options, context);\n const result = await options.executor.mutate(\n {\n resource: resourceName,\n version: String(resource.version),\n operation: operation === \"create\" ? \"insert\" : \"merge\",\n clientId,\n mutationId: args.mutationId,\n ...(args.id ? { id: args.id } : {}),\n record: args.record,\n },\n await options.context(context),\n );\n return structuredResult({ resource: resourceName, operation, result });\n },\n });\n };\n\n if (exposure.create) registerWrite(\"create\", exposure.create);\n if (exposure.update) registerWrite(\"update\", exposure.update);\n const remove = operationOptions<Omit<DatafnWriteToolOptions, \"fields\">>(\n exposure.delete,\n false,\n );\n if (remove) {\n const config = remove;\n const defaults = resourceDefaults(schema, resource);\n const writeDefault = typeof defaults === \"string\" ? defaults : defaults?.write;\n if (!resource.permissions?.write && writeDefault !== \"allResourceFields\") {\n throw new McpFnValidationError(\n `DataFn resource ${resourceName} has no write policy and cannot expose delete`,\n );\n }\n registry.register({\n name: config.name ?? defaultName(prefix, resourceName, \"delete\"),\n description: config.description ?? `Delete one ${resourceName} record by ID.`,\n inputSchema: {\n type: \"object\",\n properties: {\n id: { type: \"string\", minLength: 1 },\n mutationId: { type: \"string\", minLength: 1 },\n },\n required: [\"id\", \"mutationId\"],\n additionalProperties: false,\n },\n outputSchema: outputSchema(),\n annotations: {\n readOnlyHint: false,\n destructiveHint: true,\n idempotentHint: true,\n openWorldHint: false,\n },\n metadata: { \"mcpfn/datafn\": { resource: resourceName, operation: \"delete\" } },\n handler: async ({ id, mutationId }, context) => {\n const clientId = await resolveClientId(options, context);\n const result = await options.executor.mutate(\n {\n resource: resourceName,\n version: String(resource.version),\n operation: \"delete\",\n clientId,\n mutationId,\n id,\n },\n await options.context(context),\n );\n return structuredResult({ resource: resourceName, operation: \"delete\", result });\n },\n });\n }\n }\n\n return registry;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,kBAMO;AACP,IAAAA,eAMO;AAYP,SAAS,kBAAkB,OAAe,QAAwB;AAChE,MACE,OAAO,WAAW,KAClB,IAAI,IAAI,MAAM,EAAE,SAAS,OAAO,UAChC,OAAO,KAAK,CAAC,UAAU,OAAO,UAAU,YAAY,CAAC,KAAK,GAC1D;AACA,UAAM,IAAI,kCAAqB,GAAG,KAAK,yCAAyC;AAAA,EAClF;AACF;AAEA,SAAS,cAAc,OAAe,OAAqB;AACzD,MAAI,CAAC,OAAO,cAAc,KAAK,KAAK,QAAQ,GAAG;AAC7C,UAAM,IAAI,kCAAqB,GAAG,KAAK,kCAAkC;AAAA,EAC3E;AACF;AAEA,eAAe,gBACb,SACA,SACiB;AACjB,QAAM,WAAW,OAAO,QAAQ,aAAa,WACzC,QAAQ,WACR,MAAM,QAAQ,SAAS,OAAO;AAClC,MAAI,OAAO,aAAa,YAAY,CAAC,SAAS,KAAK,GAAG;AACpD,UAAM,IAAI,kCAAqB,oDAAoD;AAAA,EACrF;AACA,SAAO;AACT;AAEA,SAAS,YAAY,OAAuB;AAC1C,MAAI,UAAU;AACd,MAAI,iBAAiB;AACrB,aAAW,aAAa,OAAO;AAC7B,UAAM,OAAO,UAAU,WAAW,CAAC;AACnC,UAAM,UACH,QAAQ,MAAM,QAAQ,MACtB,QAAQ,MAAM,QAAQ,MACtB,QAAQ,MAAM,QAAQ,OACvB,cAAc,OAAO,cAAc,OAAO,cAAc;AAC1D,QAAI,SAAS;AACX,UAAI,kBA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,SAAS,EAAE;AAAA,QAC5E,SAAS,OAAO,EAAE,IAAI,WAAW,GAAG,YAAY;AAC9C,gBAAM,WAAW,MAAM,gBAAgB,SAAS,OAAO;AACvD,gBAAM,SAAS,MAAM,QAAQ,SAAS;AAAA,YACpC;AAAA,cACE,UAAU;AAAA,cACV,SAAS,OAAO,SAAS,OAAO;AAAA,cAChC,WAAW;AAAA,cACX;AAAA,cACA;AAAA,cACA;AAAA,YACF;AAAA,YACA,MAAM,QAAQ,QAAQ,OAAO;AAAA,UAC/B;AACA,qBAAO,+BAAiB,EAAE,UAAU,cAAc,WAAW,UAAU,OAAO,CAAC;AAAA,QACjF;AAAA,MACF,CAAC;AAAA,IACH;AAAA,EACF;AAEA,SAAO;AACT;","names":["import_core"]}
@@ -0,0 +1,46 @@
1
+ import { McpFnRegistry } from '@mcpfn/core';
2
+ import { DatafnSchema } from '@datafn/core';
3
+ import { DatafnExecutor } from '@datafn/server';
4
+
5
+ interface DatafnReadToolOptions {
6
+ name?: string;
7
+ description?: string;
8
+ }
9
+ interface DatafnListToolOptions extends DatafnReadToolOptions {
10
+ filterFields?: string[];
11
+ sortFields?: string[];
12
+ defaultLimit?: number;
13
+ maxLimit?: number;
14
+ }
15
+ interface DatafnWriteToolOptions {
16
+ name?: string;
17
+ description?: string;
18
+ fields: string[];
19
+ }
20
+ interface DatafnResourceExposure {
21
+ /** Fields returned by list/get. Explicit projection prevents schema expansion from leaking fields. */
22
+ fields: string[];
23
+ /** List and get default to enabled for an explicitly listed resource. */
24
+ list?: boolean | DatafnListToolOptions;
25
+ get?: boolean | DatafnReadToolOptions;
26
+ /** Mutations are always disabled unless configured with an explicit field allowlist. */
27
+ create?: false | DatafnWriteToolOptions;
28
+ update?: false | DatafnWriteToolOptions;
29
+ delete?: boolean | Omit<DatafnWriteToolOptions, "fields">;
30
+ }
31
+ interface CreateDatafnMcpRegistryOptions<TMcpContext, TDatafnContext> {
32
+ /** @deprecated The executor's normalized schema is authoritative. */
33
+ schema?: DatafnSchema;
34
+ executor: DatafnExecutor<TDatafnContext>;
35
+ expose: Record<string, DatafnResourceExposure>;
36
+ /** Resolve trusted DataFn context from server-derived MCP context. */
37
+ context: (context: TMcpContext) => TDatafnContext | Promise<TDatafnContext>;
38
+ /** Stable client ID used with DataFn idempotency records. */
39
+ clientId: string | ((context: TMcpContext) => string | Promise<string>);
40
+ registry?: McpFnRegistry<TMcpContext>;
41
+ toolPrefix?: string;
42
+ }
43
+
44
+ declare function createDatafnMcpRegistry<TMcpContext, TDatafnContext>(options: CreateDatafnMcpRegistryOptions<TMcpContext, TDatafnContext>): McpFnRegistry<TMcpContext>;
45
+
46
+ export { type CreateDatafnMcpRegistryOptions, type DatafnListToolOptions, type DatafnReadToolOptions, type DatafnResourceExposure, type DatafnWriteToolOptions, createDatafnMcpRegistry };
@@ -0,0 +1,46 @@
1
+ import { McpFnRegistry } from '@mcpfn/core';
2
+ import { DatafnSchema } from '@datafn/core';
3
+ import { DatafnExecutor } from '@datafn/server';
4
+
5
+ interface DatafnReadToolOptions {
6
+ name?: string;
7
+ description?: string;
8
+ }
9
+ interface DatafnListToolOptions extends DatafnReadToolOptions {
10
+ filterFields?: string[];
11
+ sortFields?: string[];
12
+ defaultLimit?: number;
13
+ maxLimit?: number;
14
+ }
15
+ interface DatafnWriteToolOptions {
16
+ name?: string;
17
+ description?: string;
18
+ fields: string[];
19
+ }
20
+ interface DatafnResourceExposure {
21
+ /** Fields returned by list/get. Explicit projection prevents schema expansion from leaking fields. */
22
+ fields: string[];
23
+ /** List and get default to enabled for an explicitly listed resource. */
24
+ list?: boolean | DatafnListToolOptions;
25
+ get?: boolean | DatafnReadToolOptions;
26
+ /** Mutations are always disabled unless configured with an explicit field allowlist. */
27
+ create?: false | DatafnWriteToolOptions;
28
+ update?: false | DatafnWriteToolOptions;
29
+ delete?: boolean | Omit<DatafnWriteToolOptions, "fields">;
30
+ }
31
+ interface CreateDatafnMcpRegistryOptions<TMcpContext, TDatafnContext> {
32
+ /** @deprecated The executor's normalized schema is authoritative. */
33
+ schema?: DatafnSchema;
34
+ executor: DatafnExecutor<TDatafnContext>;
35
+ expose: Record<string, DatafnResourceExposure>;
36
+ /** Resolve trusted DataFn context from server-derived MCP context. */
37
+ context: (context: TMcpContext) => TDatafnContext | Promise<TDatafnContext>;
38
+ /** Stable client ID used with DataFn idempotency records. */
39
+ clientId: string | ((context: TMcpContext) => string | Promise<string>);
40
+ registry?: McpFnRegistry<TMcpContext>;
41
+ toolPrefix?: string;
42
+ }
43
+
44
+ declare function createDatafnMcpRegistry<TMcpContext, TDatafnContext>(options: CreateDatafnMcpRegistryOptions<TMcpContext, TDatafnContext>): McpFnRegistry<TMcpContext>;
45
+
46
+ export { type CreateDatafnMcpRegistryOptions, type DatafnListToolOptions, type DatafnReadToolOptions, type DatafnResourceExposure, type DatafnWriteToolOptions, createDatafnMcpRegistry };
package/dist/index.js ADDED
@@ -0,0 +1,455 @@
1
+ // src/adapter.ts
2
+ import {
3
+ getCapabilityFields,
4
+ resolveCapabilities
5
+ } from "@datafn/core";
6
+ import {
7
+ McpFnRegistry,
8
+ McpFnValidationError,
9
+ structuredResult
10
+ } from "@mcpfn/core";
11
+ function validateFieldList(label, fields) {
12
+ if (fields.length === 0 || new Set(fields).size !== fields.length || fields.some((field) => typeof field !== "string" || !field)) {
13
+ throw new McpFnValidationError(`${label} must be a non-empty, unique field list`);
14
+ }
15
+ }
16
+ function validateLimit(label, value) {
17
+ if (!Number.isSafeInteger(value) || value < 1) {
18
+ throw new McpFnValidationError(`${label} must be a positive safe integer`);
19
+ }
20
+ }
21
+ async function resolveClientId(options, context) {
22
+ const clientId = typeof options.clientId === "string" ? options.clientId : await options.clientId(context);
23
+ if (typeof clientId !== "string" || !clientId.trim()) {
24
+ throw new McpFnValidationError("DataFn clientId must resolve to a non-empty string");
25
+ }
26
+ return clientId;
27
+ }
28
+ function safeSegment(value) {
29
+ let segment = "";
30
+ let needsSeparator = false;
31
+ for (const character of value) {
32
+ const code = character.charCodeAt(0);
33
+ const allowed = code >= 48 && code <= 57 || code >= 65 && code <= 90 || code >= 97 && code <= 122 || character === "_" || character === "." || character === "-";
34
+ if (allowed) {
35
+ if (needsSeparator && segment) segment += "_";
36
+ segment += character;
37
+ needsSeparator = false;
38
+ } else {
39
+ needsSeparator = true;
40
+ }
41
+ }
42
+ let start = 0;
43
+ let end = segment.length;
44
+ while (start < end && segment[start] === "_") start += 1;
45
+ while (end > start && segment[end - 1] === "_") end -= 1;
46
+ return segment.slice(start, end);
47
+ }
48
+ function resourceDefaults(schema, resource) {
49
+ if (resource.permissions !== void 0 || resource.defaultPermissions === false) {
50
+ return void 0;
51
+ }
52
+ return schema.defaultPermissions;
53
+ }
54
+ function fieldSchema(field) {
55
+ const base = (() => {
56
+ switch (field.type) {
57
+ case "number":
58
+ return { type: "number" };
59
+ case "boolean":
60
+ return { type: "boolean" };
61
+ case "array":
62
+ return { type: "array", items: {} };
63
+ case "object":
64
+ return { type: "object", additionalProperties: true };
65
+ case "json":
66
+ return { type: ["string", "number", "boolean", "object", "array"] };
67
+ case "date":
68
+ return { type: ["string", "number"], format: "date-time" };
69
+ case "file":
70
+ return { type: "string" };
71
+ default:
72
+ return { type: "string" };
73
+ }
74
+ })();
75
+ if (field.enum) base.enum = field.enum;
76
+ if (field.min !== void 0) base.minimum = field.min;
77
+ if (field.max !== void 0) base.maximum = field.max;
78
+ if (field.minLength !== void 0) base.minLength = field.minLength;
79
+ if (field.maxLength !== void 0) base.maxLength = field.maxLength;
80
+ if (field.pattern !== void 0) base.pattern = field.pattern;
81
+ if (field.nullable) {
82
+ const currentTypes = Array.isArray(base.type) ? base.type : [base.type];
83
+ base.type = [.../* @__PURE__ */ new Set([...currentTypes, "null"])];
84
+ if (Array.isArray(base.enum) && !base.enum.includes(null)) {
85
+ base.enum = [...base.enum, null];
86
+ }
87
+ }
88
+ return base;
89
+ }
90
+ function capabilitiesFor(schema, resource) {
91
+ return getCapabilityFields(
92
+ resolveCapabilities(schema.capabilities, resource.capabilities)
93
+ );
94
+ }
95
+ function fieldMaps(schema, resource) {
96
+ const schemaFields = new Map(resource.fields.map((field) => [field.name, field]));
97
+ for (const field of capabilitiesFor(schema, resource)) {
98
+ schemaFields.set(field.name, field);
99
+ }
100
+ const defaults = resourceDefaults(schema, resource);
101
+ const readDefault = typeof defaults === "string" ? defaults : defaults?.read;
102
+ const writeDefault = typeof defaults === "string" ? defaults : defaults?.write;
103
+ const defaultFields = ["id", ...resource.fields.map((field) => field.name)];
104
+ const readable = /* @__PURE__ */ new Set([
105
+ "id",
106
+ ...resource.permissions?.read?.fields ?? (readDefault === "allResourceFields" ? defaultFields : [])
107
+ ]);
108
+ for (const field of capabilitiesFor(schema, resource)) readable.add(field.name);
109
+ const writable = new Set(
110
+ resource.permissions?.write?.fields ?? (writeDefault === "allResourceFields" ? defaultFields : [])
111
+ );
112
+ return { schemaFields, readable, writable };
113
+ }
114
+ function validateReadFields(schema, resource, fields) {
115
+ const defaults = resourceDefaults(schema, resource);
116
+ const readDefault = typeof defaults === "string" ? defaults : defaults?.read;
117
+ if (!resource.permissions?.read && readDefault !== "allResourceFields") {
118
+ throw new McpFnValidationError(
119
+ `DataFn resource ${resource.name} has no read policy and cannot be exposed`
120
+ );
121
+ }
122
+ const { schemaFields, readable } = fieldMaps(schema, resource);
123
+ for (const field of fields) {
124
+ if (field !== "id" && !schemaFields.has(field)) {
125
+ throw new McpFnValidationError(
126
+ `Unknown exposed field ${resource.name}.${field}`
127
+ );
128
+ }
129
+ if (!readable.has(field)) {
130
+ throw new McpFnValidationError(
131
+ `Field ${resource.name}.${field} is not readable by DataFn policy`
132
+ );
133
+ }
134
+ }
135
+ }
136
+ function validateWriteFields(schema, resource, fields) {
137
+ const defaults = resourceDefaults(schema, resource);
138
+ const writeDefault = typeof defaults === "string" ? defaults : defaults?.write;
139
+ if (!resource.permissions?.write && writeDefault !== "allResourceFields") {
140
+ throw new McpFnValidationError(
141
+ `DataFn resource ${resource.name} has no write policy and cannot expose mutations`
142
+ );
143
+ }
144
+ const { schemaFields, writable } = fieldMaps(schema, resource);
145
+ for (const field of fields) {
146
+ const definition = schemaFields.get(field);
147
+ if (!definition) {
148
+ throw new McpFnValidationError(`Unknown write field ${resource.name}.${field}`);
149
+ }
150
+ if (definition.readonly || !writable.has(field)) {
151
+ throw new McpFnValidationError(
152
+ `Field ${resource.name}.${field} is not writable by DataFn policy`
153
+ );
154
+ }
155
+ }
156
+ }
157
+ function operationOptions(value, enabledByDefault) {
158
+ if (value === false) return void 0;
159
+ if (value === true) return {};
160
+ if (value === void 0) return enabledByDefault ? {} : void 0;
161
+ return value;
162
+ }
163
+ function outputSchema() {
164
+ return {
165
+ type: "object",
166
+ properties: {
167
+ resource: { type: "string" },
168
+ operation: { type: "string" },
169
+ result: {}
170
+ },
171
+ required: ["resource", "operation", "result"],
172
+ additionalProperties: false
173
+ };
174
+ }
175
+ function defaultName(prefix, resource, operation) {
176
+ return [prefix, safeSegment(resource), operation].filter(Boolean).join("_");
177
+ }
178
+ function assertUniqueToolNames(registry, expose, prefix) {
179
+ const owners = /* @__PURE__ */ new Map();
180
+ for (const resourceName of Object.keys(expose).sort()) {
181
+ const exposure = expose[resourceName];
182
+ const operations = [
183
+ ["list", operationOptions(exposure.list, true)],
184
+ ["get", operationOptions(exposure.get, true)],
185
+ ["create", exposure.create || void 0],
186
+ ["update", exposure.update || void 0],
187
+ ["delete", operationOptions(exposure.delete, false)]
188
+ ];
189
+ for (const [operation, config] of operations) {
190
+ if (!config) continue;
191
+ const name = config.name ?? defaultName(prefix, resourceName, operation);
192
+ const owner = `${resourceName}.${operation}`;
193
+ const existing = owners.get(name);
194
+ if (existing || registry.has(name)) {
195
+ throw new McpFnValidationError(
196
+ `DataFn tool name collision for ${name}: ${existing ?? "existing registry tool"} and ${owner}`
197
+ );
198
+ }
199
+ owners.set(name, owner);
200
+ }
201
+ }
202
+ }
203
+ function createDatafnMcpRegistry(options) {
204
+ const registry = options.registry ?? new McpFnRegistry();
205
+ const schema = options.executor.schema;
206
+ const prefix = safeSegment(options.toolPrefix ?? "datafn");
207
+ if (typeof options.clientId === "string" && !options.clientId.trim()) {
208
+ throw new McpFnValidationError("DataFn clientId must be a non-empty string");
209
+ }
210
+ assertUniqueToolNames(registry, options.expose, prefix);
211
+ for (const resourceName of Object.keys(options.expose).sort()) {
212
+ const exposure = options.expose[resourceName];
213
+ const resource = schema.resources.find((candidate) => candidate.name === resourceName);
214
+ if (!resource) {
215
+ throw new McpFnValidationError(`Unknown DataFn resource: ${resourceName}`);
216
+ }
217
+ const list = operationOptions(exposure.list, true);
218
+ const get = operationOptions(exposure.get, true);
219
+ validateFieldList(`DataFn resource ${resourceName} projection`, exposure.fields);
220
+ if (list || get) validateReadFields(schema, resource, exposure.fields);
221
+ const maps = fieldMaps(schema, resource);
222
+ if (list) {
223
+ const filterFields = list.filterFields ?? exposure.fields;
224
+ const sortFields = list.sortFields ?? ["id"];
225
+ validateFieldList(`DataFn resource ${resourceName} filterFields`, filterFields);
226
+ validateFieldList(`DataFn resource ${resourceName} sortFields`, sortFields);
227
+ validateReadFields(schema, resource, [...filterFields, ...sortFields]);
228
+ const filterProperties = Object.fromEntries(
229
+ filterFields.map((field) => [
230
+ field,
231
+ field === "id" ? { type: "string" } : fieldSchema(maps.schemaFields.get(field))
232
+ ])
233
+ );
234
+ const maxLimit = list.maxLimit ?? 100;
235
+ validateLimit(`DataFn resource ${resourceName} maxLimit`, maxLimit);
236
+ const defaultLimit = list.defaultLimit ?? Math.min(50, maxLimit);
237
+ validateLimit(`DataFn resource ${resourceName} defaultLimit`, defaultLimit);
238
+ if (defaultLimit > maxLimit) {
239
+ throw new McpFnValidationError(
240
+ `DataFn resource ${resourceName} defaultLimit cannot exceed maxLimit`
241
+ );
242
+ }
243
+ const definition = {
244
+ name: list.name ?? defaultName(prefix, resourceName, "list"),
245
+ description: list.description ?? `List ${resourceName} records visible to the authenticated DataFn context.`,
246
+ inputSchema: {
247
+ type: "object",
248
+ properties: {
249
+ filters: {
250
+ type: "object",
251
+ properties: filterProperties,
252
+ additionalProperties: false
253
+ },
254
+ sort: {
255
+ type: "array",
256
+ items: {
257
+ type: "string",
258
+ enum: sortFields.flatMap((field) => [`${field}:asc`, `${field}:desc`])
259
+ },
260
+ maxItems: Math.max(1, sortFields.length)
261
+ },
262
+ cursor: { type: "object", additionalProperties: true },
263
+ limit: { type: "integer", minimum: 1, maximum: maxLimit }
264
+ },
265
+ additionalProperties: false
266
+ },
267
+ outputSchema: outputSchema(),
268
+ annotations: {
269
+ readOnlyHint: true,
270
+ destructiveHint: false,
271
+ idempotentHint: true,
272
+ openWorldHint: false
273
+ },
274
+ metadata: { "mcpfn/datafn": { resource: resourceName, operation: "list" } },
275
+ handler: async (args, context) => {
276
+ const requestedSort = args.sort;
277
+ const querySort = requestedSort?.length ? [
278
+ ...requestedSort.filter((term) => !term.startsWith("id:")),
279
+ requestedSort.find((term) => term.startsWith("id:")) ?? "id:asc"
280
+ ] : void 0;
281
+ const result = await options.executor.query(
282
+ {
283
+ resource: resourceName,
284
+ version: String(resource.version),
285
+ select: exposure.fields,
286
+ ...args.filters ? { filters: args.filters } : {},
287
+ ...querySort ? { sort: querySort } : {},
288
+ ...args.cursor ? { cursor: args.cursor } : {},
289
+ limit: Math.min(Number(args.limit ?? defaultLimit), maxLimit)
290
+ },
291
+ await options.context(context)
292
+ );
293
+ return structuredResult({ resource: resourceName, operation: "list", result });
294
+ }
295
+ };
296
+ registry.register(definition);
297
+ }
298
+ if (get) {
299
+ registry.register({
300
+ name: get.name ?? defaultName(prefix, resourceName, "get"),
301
+ description: get.description ?? `Get one ${resourceName} record by ID.`,
302
+ inputSchema: {
303
+ type: "object",
304
+ properties: { id: { type: "string", minLength: 1 } },
305
+ required: ["id"],
306
+ additionalProperties: false
307
+ },
308
+ outputSchema: outputSchema(),
309
+ annotations: {
310
+ readOnlyHint: true,
311
+ destructiveHint: false,
312
+ idempotentHint: true,
313
+ openWorldHint: false
314
+ },
315
+ metadata: { "mcpfn/datafn": { resource: resourceName, operation: "get" } },
316
+ handler: async ({ id }, context) => {
317
+ const result = await options.executor.query(
318
+ {
319
+ resource: resourceName,
320
+ version: String(resource.version),
321
+ select: exposure.fields,
322
+ filters: { id },
323
+ limit: 1
324
+ },
325
+ await options.context(context)
326
+ );
327
+ return structuredResult({ resource: resourceName, operation: "get", result });
328
+ }
329
+ });
330
+ }
331
+ const registerWrite = (operation, config) => {
332
+ validateFieldList(
333
+ `DataFn resource ${resourceName} ${operation} fields`,
334
+ config.fields
335
+ );
336
+ validateWriteFields(schema, resource, config.fields);
337
+ const requiredCreateFields = [...maps.schemaFields.values()].filter((field) => field.name !== "id" && field.required && field.default === void 0 && !field.readonly).map((field) => field.name).sort();
338
+ if (operation === "create") {
339
+ const missingRequiredFields = requiredCreateFields.filter(
340
+ (field) => !config.fields.includes(field)
341
+ );
342
+ if (missingRequiredFields.length) {
343
+ throw new McpFnValidationError(
344
+ `DataFn resource ${resourceName} create fields omit required writable fields: ${missingRequiredFields.join(", ")}`
345
+ );
346
+ }
347
+ }
348
+ const properties = Object.fromEntries(
349
+ config.fields.map((field) => [field, fieldSchema(maps.schemaFields.get(field))])
350
+ );
351
+ const recordRequired = operation === "create" ? requiredCreateFields : [];
352
+ registry.register({
353
+ name: config.name ?? defaultName(prefix, resourceName, operation),
354
+ description: config.description ?? `${operation === "create" ? "Create" : "Update"} one ${resourceName} record.`,
355
+ inputSchema: {
356
+ type: "object",
357
+ properties: {
358
+ ...operation === "create" ? { id: { type: "string", minLength: 1 } } : {},
359
+ ...operation === "update" ? { id: { type: "string", minLength: 1 } } : {},
360
+ mutationId: { type: "string", minLength: 1 },
361
+ record: {
362
+ type: "object",
363
+ properties,
364
+ ...recordRequired.length ? { required: recordRequired } : {},
365
+ additionalProperties: false
366
+ }
367
+ },
368
+ required: ["mutationId", "record", ...operation === "update" ? ["id"] : []],
369
+ additionalProperties: false
370
+ },
371
+ outputSchema: outputSchema(),
372
+ annotations: {
373
+ readOnlyHint: false,
374
+ destructiveHint: false,
375
+ idempotentHint: true,
376
+ openWorldHint: false
377
+ },
378
+ metadata: { "mcpfn/datafn": { resource: resourceName, operation } },
379
+ handler: async (args, context) => {
380
+ const clientId = await resolveClientId(options, context);
381
+ const result = await options.executor.mutate(
382
+ {
383
+ resource: resourceName,
384
+ version: String(resource.version),
385
+ operation: operation === "create" ? "insert" : "merge",
386
+ clientId,
387
+ mutationId: args.mutationId,
388
+ ...args.id ? { id: args.id } : {},
389
+ record: args.record
390
+ },
391
+ await options.context(context)
392
+ );
393
+ return structuredResult({ resource: resourceName, operation, result });
394
+ }
395
+ });
396
+ };
397
+ if (exposure.create) registerWrite("create", exposure.create);
398
+ if (exposure.update) registerWrite("update", exposure.update);
399
+ const remove = operationOptions(
400
+ exposure.delete,
401
+ false
402
+ );
403
+ if (remove) {
404
+ const config = remove;
405
+ const defaults = resourceDefaults(schema, resource);
406
+ const writeDefault = typeof defaults === "string" ? defaults : defaults?.write;
407
+ if (!resource.permissions?.write && writeDefault !== "allResourceFields") {
408
+ throw new McpFnValidationError(
409
+ `DataFn resource ${resourceName} has no write policy and cannot expose delete`
410
+ );
411
+ }
412
+ registry.register({
413
+ name: config.name ?? defaultName(prefix, resourceName, "delete"),
414
+ description: config.description ?? `Delete one ${resourceName} record by ID.`,
415
+ inputSchema: {
416
+ type: "object",
417
+ properties: {
418
+ id: { type: "string", minLength: 1 },
419
+ mutationId: { type: "string", minLength: 1 }
420
+ },
421
+ required: ["id", "mutationId"],
422
+ additionalProperties: false
423
+ },
424
+ outputSchema: outputSchema(),
425
+ annotations: {
426
+ readOnlyHint: false,
427
+ destructiveHint: true,
428
+ idempotentHint: true,
429
+ openWorldHint: false
430
+ },
431
+ metadata: { "mcpfn/datafn": { resource: resourceName, operation: "delete" } },
432
+ handler: async ({ id, mutationId }, context) => {
433
+ const clientId = await resolveClientId(options, context);
434
+ const result = await options.executor.mutate(
435
+ {
436
+ resource: resourceName,
437
+ version: String(resource.version),
438
+ operation: "delete",
439
+ clientId,
440
+ mutationId,
441
+ id
442
+ },
443
+ await options.context(context)
444
+ );
445
+ return structuredResult({ resource: resourceName, operation: "delete", result });
446
+ }
447
+ });
448
+ }
449
+ }
450
+ return registry;
451
+ }
452
+ export {
453
+ createDatafnMcpRegistry
454
+ };
455
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/adapter.ts"],"sourcesContent":["import {\n getCapabilityFields,\n resolveCapabilities,\n type DatafnFieldSchema,\n type DatafnResourceSchema,\n type DatafnSchema,\n} from \"@datafn/core\";\nimport {\n McpFnRegistry,\n McpFnValidationError,\n structuredResult,\n type McpFnJsonSchema,\n type McpFnToolDefinition,\n} from \"@mcpfn/core\";\n\nimport type {\n CreateDatafnMcpRegistryOptions,\n DatafnListToolOptions,\n DatafnReadToolOptions,\n DatafnResourceExposure,\n DatafnWriteToolOptions,\n} from \"./types.js\";\n\ntype Operation = \"list\" | \"get\" | \"create\" | \"update\" | \"delete\";\n\nfunction validateFieldList(label: string, fields: string[]): void {\n if (\n fields.length === 0 ||\n new Set(fields).size !== fields.length ||\n fields.some((field) => typeof field !== \"string\" || !field)\n ) {\n throw new McpFnValidationError(`${label} must be a non-empty, unique field list`);\n }\n}\n\nfunction validateLimit(label: string, value: number): void {\n if (!Number.isSafeInteger(value) || value < 1) {\n throw new McpFnValidationError(`${label} must be a positive safe integer`);\n }\n}\n\nasync function resolveClientId<TMcpContext, TDatafnContext>(\n options: CreateDatafnMcpRegistryOptions<TMcpContext, TDatafnContext>,\n context: TMcpContext,\n): Promise<string> {\n const clientId = typeof options.clientId === \"string\"\n ? options.clientId\n : await options.clientId(context);\n if (typeof clientId !== \"string\" || !clientId.trim()) {\n throw new McpFnValidationError(\"DataFn clientId must resolve to a non-empty string\");\n }\n return clientId;\n}\n\nfunction safeSegment(value: string): string {\n let segment = \"\";\n let needsSeparator = false;\n for (const character of value) {\n const code = character.charCodeAt(0);\n const allowed =\n (code >= 48 && code <= 57) ||\n (code >= 65 && code <= 90) ||\n (code >= 97 && code <= 122) ||\n character === \"_\" || character === \".\" || character === \"-\";\n if (allowed) {\n if (needsSeparator && segment) segment += \"_\";\n segment += character;\n needsSeparator = false;\n } else {\n needsSeparator = true;\n }\n }\n let start = 0;\n let end = segment.length;\n while (start < end && segment[start] === \"_\") start += 1;\n while (end > start && segment[end - 1] === \"_\") end -= 1;\n return segment.slice(start, end);\n}\n\nfunction resourceDefaults(\n schema: DatafnSchema,\n resource: DatafnResourceSchema,\n) {\n if (resource.permissions !== undefined || resource.defaultPermissions === false) {\n return undefined;\n }\n return schema.defaultPermissions;\n}\n\nfunction fieldSchema(field: DatafnFieldSchema): McpFnJsonSchema {\n const base: McpFnJsonSchema = (() => {\n switch (field.type) {\n case \"number\": return { type: \"number\" };\n case \"boolean\": return { type: \"boolean\" };\n case \"array\": return { type: \"array\", items: {} };\n case \"object\": return { type: \"object\", additionalProperties: true };\n case \"json\": return { type: [\"string\", \"number\", \"boolean\", \"object\", \"array\"] };\n case \"date\": return { type: [\"string\", \"number\"], format: \"date-time\" };\n case \"file\": return { type: \"string\" };\n default: return { type: \"string\" };\n }\n })();\n if (field.enum) base.enum = field.enum;\n if (field.min !== undefined) base.minimum = field.min;\n if (field.max !== undefined) base.maximum = field.max;\n if (field.minLength !== undefined) base.minLength = field.minLength;\n if (field.maxLength !== undefined) base.maxLength = field.maxLength;\n if (field.pattern !== undefined) base.pattern = field.pattern;\n if (field.nullable) {\n const currentTypes = Array.isArray(base.type) ? base.type : [base.type];\n base.type = [...new Set([...currentTypes, \"null\"])];\n if (Array.isArray(base.enum) && !base.enum.includes(null)) {\n base.enum = [...base.enum, null];\n }\n }\n return base;\n}\n\nfunction capabilitiesFor(\n schema: DatafnSchema,\n resource: DatafnResourceSchema,\n) {\n return getCapabilityFields(\n resolveCapabilities(schema.capabilities as never, resource.capabilities as never) as never,\n );\n}\n\nfunction fieldMaps(\n schema: DatafnSchema,\n resource: DatafnResourceSchema,\n) {\n const schemaFields = new Map(resource.fields.map((field) => [field.name, field]));\n for (const field of capabilitiesFor(schema, resource)) {\n schemaFields.set(field.name, field as DatafnFieldSchema);\n }\n const defaults = resourceDefaults(schema, resource);\n const readDefault = typeof defaults === \"string\" ? defaults : defaults?.read;\n const writeDefault = typeof defaults === \"string\" ? defaults : defaults?.write;\n const defaultFields = [\"id\", ...resource.fields.map((field) => field.name)];\n const readable = new Set([\n \"id\",\n ...(resource.permissions?.read?.fields ??\n (readDefault === \"allResourceFields\" ? defaultFields : [])),\n ]);\n for (const field of capabilitiesFor(schema, resource)) readable.add(field.name);\n const writable = new Set(\n resource.permissions?.write?.fields ??\n (writeDefault === \"allResourceFields\" ? defaultFields : []),\n );\n return { schemaFields, readable, writable };\n}\n\nfunction validateReadFields(\n schema: DatafnSchema,\n resource: DatafnResourceSchema,\n fields: string[],\n): void {\n const defaults = resourceDefaults(schema, resource);\n const readDefault = typeof defaults === \"string\" ? defaults : defaults?.read;\n if (!resource.permissions?.read && readDefault !== \"allResourceFields\") {\n throw new McpFnValidationError(\n `DataFn resource ${resource.name} has no read policy and cannot be exposed`,\n );\n }\n const { schemaFields, readable } = fieldMaps(schema, resource);\n for (const field of fields) {\n if (field !== \"id\" && !schemaFields.has(field)) {\n throw new McpFnValidationError(\n `Unknown exposed field ${resource.name}.${field}`,\n );\n }\n if (!readable.has(field)) {\n throw new McpFnValidationError(\n `Field ${resource.name}.${field} is not readable by DataFn policy`,\n );\n }\n }\n}\n\nfunction validateWriteFields(\n schema: DatafnSchema,\n resource: DatafnResourceSchema,\n fields: string[],\n): void {\n const defaults = resourceDefaults(schema, resource);\n const writeDefault = typeof defaults === \"string\" ? defaults : defaults?.write;\n if (!resource.permissions?.write && writeDefault !== \"allResourceFields\") {\n throw new McpFnValidationError(\n `DataFn resource ${resource.name} has no write policy and cannot expose mutations`,\n );\n }\n const { schemaFields, writable } = fieldMaps(schema, resource);\n for (const field of fields) {\n const definition = schemaFields.get(field);\n if (!definition) {\n throw new McpFnValidationError(`Unknown write field ${resource.name}.${field}`);\n }\n if (definition.readonly || !writable.has(field)) {\n throw new McpFnValidationError(\n `Field ${resource.name}.${field} is not writable by DataFn policy`,\n );\n }\n }\n}\n\nfunction operationOptions<T>(value: boolean | T | undefined, enabledByDefault: boolean): T | undefined {\n if (value === false) return undefined;\n if (value === true) return {} as T;\n if (value === undefined) return enabledByDefault ? ({} as T) : undefined;\n return value;\n}\n\nfunction outputSchema() {\n return {\n type: \"object\" as const,\n properties: {\n resource: { type: \"string\" },\n operation: { type: \"string\" },\n result: {},\n },\n required: [\"resource\", \"operation\", \"result\"],\n additionalProperties: false,\n };\n}\n\nfunction defaultName(prefix: string, resource: string, operation: Operation): string {\n return [prefix, safeSegment(resource), operation].filter(Boolean).join(\"_\");\n}\n\nfunction assertUniqueToolNames<TMcpContext>(\n registry: McpFnRegistry<TMcpContext>,\n expose: Record<string, DatafnResourceExposure>,\n prefix: string,\n): void {\n const owners = new Map<string, string>();\n for (const resourceName of Object.keys(expose).sort()) {\n const exposure = expose[resourceName]!;\n const operations: Array<[Operation, DatafnReadToolOptions | DatafnWriteToolOptions | undefined]> = [\n [\"list\", operationOptions<DatafnListToolOptions>(exposure.list, true)],\n [\"get\", operationOptions<DatafnReadToolOptions>(exposure.get, true)],\n [\"create\", exposure.create || undefined],\n [\"update\", exposure.update || undefined],\n [\"delete\", operationOptions<Omit<DatafnWriteToolOptions, \"fields\">>(exposure.delete, false)],\n ];\n for (const [operation, config] of operations) {\n if (!config) continue;\n const name = config.name ?? defaultName(prefix, resourceName, operation);\n const owner = `${resourceName}.${operation}`;\n const existing = owners.get(name);\n if (existing || registry.has(name)) {\n throw new McpFnValidationError(\n `DataFn tool name collision for ${name}: ${existing ?? \"existing registry tool\"} and ${owner}`,\n );\n }\n owners.set(name, owner);\n }\n }\n}\n\nexport function createDatafnMcpRegistry<TMcpContext, TDatafnContext>(\n options: CreateDatafnMcpRegistryOptions<TMcpContext, TDatafnContext>,\n): McpFnRegistry<TMcpContext> {\n const registry = options.registry ?? new McpFnRegistry<TMcpContext>();\n const schema = options.executor.schema;\n const prefix = safeSegment(options.toolPrefix ?? \"datafn\");\n if (typeof options.clientId === \"string\" && !options.clientId.trim()) {\n throw new McpFnValidationError(\"DataFn clientId must be a non-empty string\");\n }\n assertUniqueToolNames(registry, options.expose, prefix);\n\n for (const resourceName of Object.keys(options.expose).sort()) {\n const exposure = options.expose[resourceName]!;\n const resource = schema.resources.find((candidate) => candidate.name === resourceName);\n if (!resource) {\n throw new McpFnValidationError(`Unknown DataFn resource: ${resourceName}`);\n }\n const list = operationOptions<DatafnListToolOptions>(exposure.list, true);\n const get = operationOptions<DatafnReadToolOptions>(exposure.get, true);\n validateFieldList(`DataFn resource ${resourceName} projection`, exposure.fields);\n if (list || get) validateReadFields(schema, resource, exposure.fields);\n const maps = fieldMaps(schema, resource);\n\n if (list) {\n const filterFields = list.filterFields ?? exposure.fields;\n const sortFields = list.sortFields ?? [\"id\"];\n validateFieldList(`DataFn resource ${resourceName} filterFields`, filterFields);\n validateFieldList(`DataFn resource ${resourceName} sortFields`, sortFields);\n validateReadFields(schema, resource, [...filterFields, ...sortFields]);\n const filterProperties = Object.fromEntries(\n filterFields.map((field) => [\n field,\n field === \"id\" ? { type: \"string\" } : fieldSchema(maps.schemaFields.get(field)!),\n ]),\n );\n const maxLimit = list.maxLimit ?? 100;\n validateLimit(`DataFn resource ${resourceName} maxLimit`, maxLimit);\n const defaultLimit = list.defaultLimit ?? Math.min(50, maxLimit);\n validateLimit(`DataFn resource ${resourceName} defaultLimit`, defaultLimit);\n if (defaultLimit > maxLimit) {\n throw new McpFnValidationError(\n `DataFn resource ${resourceName} defaultLimit cannot exceed maxLimit`,\n );\n }\n const definition: McpFnToolDefinition<TMcpContext> = {\n name: list.name ?? defaultName(prefix, resourceName, \"list\"),\n description:\n list.description ?? `List ${resourceName} records visible to the authenticated DataFn context.`,\n inputSchema: {\n type: \"object\",\n properties: {\n filters: {\n type: \"object\",\n properties: filterProperties,\n additionalProperties: false,\n },\n sort: {\n type: \"array\",\n items: {\n type: \"string\",\n enum: sortFields.flatMap((field) => [`${field}:asc`, `${field}:desc`]),\n },\n maxItems: Math.max(1, sortFields.length),\n },\n cursor: { type: \"object\", additionalProperties: true },\n limit: { type: \"integer\", minimum: 1, maximum: maxLimit },\n },\n additionalProperties: false,\n },\n outputSchema: outputSchema(),\n annotations: {\n readOnlyHint: true,\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: false,\n },\n metadata: { \"mcpfn/datafn\": { resource: resourceName, operation: \"list\" } },\n handler: async (args, context) => {\n const requestedSort = args.sort as string[] | undefined;\n const querySort = requestedSort?.length\n ? [\n ...requestedSort.filter((term) => !term.startsWith(\"id:\")),\n requestedSort.find((term) => term.startsWith(\"id:\")) ?? \"id:asc\",\n ]\n : undefined;\n const result = await options.executor.query(\n {\n resource: resourceName,\n version: String(resource.version),\n select: exposure.fields,\n ...(args.filters ? { filters: args.filters } : {}),\n ...(querySort ? { sort: querySort } : {}),\n ...(args.cursor ? { cursor: args.cursor } : {}),\n limit: Math.min(Number(args.limit ?? defaultLimit), maxLimit),\n },\n await options.context(context),\n );\n return structuredResult({ resource: resourceName, operation: \"list\", result });\n },\n };\n registry.register(definition);\n }\n\n if (get) {\n registry.register({\n name: get.name ?? defaultName(prefix, resourceName, \"get\"),\n description: get.description ?? `Get one ${resourceName} record by ID.`,\n inputSchema: {\n type: \"object\",\n properties: { id: { type: \"string\", minLength: 1 } },\n required: [\"id\"],\n additionalProperties: false,\n },\n outputSchema: outputSchema(),\n annotations: {\n readOnlyHint: true,\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: false,\n },\n metadata: { \"mcpfn/datafn\": { resource: resourceName, operation: \"get\" } },\n handler: async ({ id }, context) => {\n const result = await options.executor.query(\n {\n resource: resourceName,\n version: String(resource.version),\n select: exposure.fields,\n filters: { id },\n limit: 1,\n },\n await options.context(context),\n );\n return structuredResult({ resource: resourceName, operation: \"get\", result });\n },\n });\n }\n\n const registerWrite = (\n operation: \"create\" | \"update\",\n config: DatafnWriteToolOptions,\n ) => {\n validateFieldList(\n `DataFn resource ${resourceName} ${operation} fields`,\n config.fields,\n );\n validateWriteFields(schema, resource, config.fields);\n const requiredCreateFields = [...maps.schemaFields.values()]\n .filter((field) =>\n field.name !== \"id\" &&\n field.required &&\n field.default === undefined &&\n !field.readonly)\n .map((field) => field.name)\n .sort();\n if (operation === \"create\") {\n const missingRequiredFields = requiredCreateFields.filter(\n (field) => !config.fields.includes(field),\n );\n if (missingRequiredFields.length) {\n throw new McpFnValidationError(\n `DataFn resource ${resourceName} create fields omit required writable fields: ${missingRequiredFields.join(\", \")}`,\n );\n }\n }\n const properties = Object.fromEntries(\n config.fields.map((field) => [field, fieldSchema(maps.schemaFields.get(field)!)]),\n );\n const recordRequired = operation === \"create\"\n ? requiredCreateFields\n : [];\n registry.register({\n name: config.name ?? defaultName(prefix, resourceName, operation),\n description: config.description ?? `${operation === \"create\" ? \"Create\" : \"Update\"} one ${resourceName} record.`,\n inputSchema: {\n type: \"object\",\n properties: {\n ...(operation === \"create\" ? { id: { type: \"string\", minLength: 1 } } : {}),\n ...(operation === \"update\" ? { id: { type: \"string\", minLength: 1 } } : {}),\n mutationId: { type: \"string\", minLength: 1 },\n record: {\n type: \"object\",\n properties,\n ...(recordRequired.length ? { required: recordRequired } : {}),\n additionalProperties: false,\n },\n },\n required: [\"mutationId\", \"record\", ...(operation === \"update\" ? [\"id\"] : [])],\n additionalProperties: false,\n },\n outputSchema: outputSchema(),\n annotations: {\n readOnlyHint: false,\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: false,\n },\n metadata: { \"mcpfn/datafn\": { resource: resourceName, operation } },\n handler: async (args, context) => {\n const clientId = await resolveClientId(options, context);\n const result = await options.executor.mutate(\n {\n resource: resourceName,\n version: String(resource.version),\n operation: operation === \"create\" ? \"insert\" : \"merge\",\n clientId,\n mutationId: args.mutationId,\n ...(args.id ? { id: args.id } : {}),\n record: args.record,\n },\n await options.context(context),\n );\n return structuredResult({ resource: resourceName, operation, result });\n },\n });\n };\n\n if (exposure.create) registerWrite(\"create\", exposure.create);\n if (exposure.update) registerWrite(\"update\", exposure.update);\n const remove = operationOptions<Omit<DatafnWriteToolOptions, \"fields\">>(\n exposure.delete,\n false,\n );\n if (remove) {\n const config = remove;\n const defaults = resourceDefaults(schema, resource);\n const writeDefault = typeof defaults === \"string\" ? defaults : defaults?.write;\n if (!resource.permissions?.write && writeDefault !== \"allResourceFields\") {\n throw new McpFnValidationError(\n `DataFn resource ${resourceName} has no write policy and cannot expose delete`,\n );\n }\n registry.register({\n name: config.name ?? defaultName(prefix, resourceName, \"delete\"),\n description: config.description ?? `Delete one ${resourceName} record by ID.`,\n inputSchema: {\n type: \"object\",\n properties: {\n id: { type: \"string\", minLength: 1 },\n mutationId: { type: \"string\", minLength: 1 },\n },\n required: [\"id\", \"mutationId\"],\n additionalProperties: false,\n },\n outputSchema: outputSchema(),\n annotations: {\n readOnlyHint: false,\n destructiveHint: true,\n idempotentHint: true,\n openWorldHint: false,\n },\n metadata: { \"mcpfn/datafn\": { resource: resourceName, operation: \"delete\" } },\n handler: async ({ id, mutationId }, context) => {\n const clientId = await resolveClientId(options, context);\n const result = await options.executor.mutate(\n {\n resource: resourceName,\n version: String(resource.version),\n operation: \"delete\",\n clientId,\n mutationId,\n id,\n },\n await options.context(context),\n );\n return structuredResult({ resource: resourceName, operation: \"delete\", result });\n },\n });\n }\n }\n\n return registry;\n}\n"],"mappings":";AAAA;AAAA,EACE;AAAA,EACA;AAAA,OAIK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OAGK;AAYP,SAAS,kBAAkB,OAAe,QAAwB;AAChE,MACE,OAAO,WAAW,KAClB,IAAI,IAAI,MAAM,EAAE,SAAS,OAAO,UAChC,OAAO,KAAK,CAAC,UAAU,OAAO,UAAU,YAAY,CAAC,KAAK,GAC1D;AACA,UAAM,IAAI,qBAAqB,GAAG,KAAK,yCAAyC;AAAA,EAClF;A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ny-by-default DataFn resource exposure for McpFn",
5
+ "type": "module",
6
+ "main": "dist/index.cjs",
7
+ "module": "dist/index.js",
8
+ "types": "dist/index.d.ts",
9
+ "exports": {
10
+ ".": {
11
+ "types": "./dist/index.d.ts",
12
+ "import": "./dist/index.js",
13
+ "require": "./dist/index.cjs"
14
+ }
15
+ },
16
+ "files": ["dist", "README.md"],
17
+ "scripts": {
18
+ "build": "tsup",
19
+ "clean": "node --input-type=module -e \"import('node:fs').then(({ rmSync }) => rmSync('dist', { recursive: true, force: true }))\"",
20
+ "lint": "tsc --noEmit",
21
+ "test": "vitest run",
22
+ "typecheck": "tsc --noEmit"
23
+ },
24
+ "dependencies": {
25
+ "@datafn/core": "0.1.0",
26
+ "@datafn/server": "0.1.0",
27
+ "@mcpfn/core": "0.0.1"
28
+ },
29
+ "devDependencies": {
30
+ "@superfunctions/db": "0.2.0",
31
+ "@mcpfn/testing": "0.0.1",
32
+ "@types/node": "^20.0.0",
33
+ "tsup": "^8.5.0",
34
+ "typescript": "^5.9.3",
35
+ "vitest": "^3.2.4"
36
+ },
37
+ "engines": { "node": ">=18.18.0" },
38
+ "license": "MIT",
39
+ "repository": {
40
+ "type": "git",
41
+ "url": "git+https://github.com/21nCo/super-functions.git",
42
+ "directory": "mcpfn/datafn"
43
+ },
44
+ "publishConfig": { "access": "public" },
45
+ "sideEffects": false
46
+ }