@adminforge/ai 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,19 @@
1
+
2
+ > @adminforge/ai@0.2.0 build /home/runner/work/AdminForge/AdminForge/packages/ai
3
+ > tsup
4
+
5
+ CLI Building entry: src/cli.ts, src/index.ts
6
+ CLI Using tsconfig: tsconfig.json
7
+ CLI tsup v8.5.1
8
+ CLI Using tsup config: /home/runner/work/AdminForge/AdminForge/packages/ai/tsup.config.ts
9
+ CLI Target: es2022
10
+ CLI Cleaning output folder
11
+ ESM Build start
12
+ ESM dist/cli.js 2.04 KB
13
+ ESM dist/chunk-QNQC6QCL.js 372.00 B
14
+ ESM dist/index.js 10.26 KB
15
+ ESM ⚡️ Build success in 17ms
16
+ DTS Build start
17
+ DTS ⚡️ Build success in 2659ms
18
+ DTS dist/cli.d.ts 13.00 B
19
+ DTS dist/index.d.ts 13.00 B
package/CHANGELOG.md ADDED
@@ -0,0 +1,14 @@
1
+ # @adminforge/ai
2
+
3
+ ## 0.2.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 473b0a5: Added high-level helpers, CLI migrate command, and media upload support.
8
+ - 9ddaafa: Initial public release of the AdminForge ecosystem. Includes unified core framework and AI orchestration layer.
9
+
10
+ ### Patch Changes
11
+
12
+ - Updated dependencies [473b0a5]
13
+ - Updated dependencies [9ddaafa]
14
+ - adminforge@0.2.0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 AdminForge Contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,10 @@
1
+ // ../../node_modules/.pnpm/tsup@8.5.1_jiti@2.7.0_postcss@8.4.31_tsx@4.21.0_typescript@5.9.3/node_modules/tsup/assets/esm_shims.js
2
+ import path from "path";
3
+ import { fileURLToPath } from "url";
4
+ var getFilename = () => fileURLToPath(import.meta.url);
5
+ var getDirname = () => path.dirname(getFilename());
6
+ var __dirname = /* @__PURE__ */ getDirname();
7
+
8
+ export {
9
+ __dirname
10
+ };
package/dist/cli.d.ts ADDED
@@ -0,0 +1,2 @@
1
+
2
+ export { }
package/dist/cli.js ADDED
@@ -0,0 +1,41 @@
1
+ import {
2
+ __dirname
3
+ } from "./chunk-QNQC6QCL.js";
4
+
5
+ // src/cli.ts
6
+ import { Command } from "commander";
7
+ import { generateAgentToken } from "adminforge/next";
8
+ import { spawn } from "child_process";
9
+ import path from "path";
10
+ var program = new Command();
11
+ program.name("adminforge-ai").description("CLI to manage AdminForge AI Orchestration and MCP Server").version("0.2.0");
12
+ program.command("start").description("Start the MCP server on stdio").option("-c, --config <path>", "Path to adminforge.ts", "./adminforge.ts").option("-u, --api-url <url>", "Remote AdminForge API URL (Proxy Mode)").option("-t, --token <token>", "Agent Token for Proxy Mode").option("-d, --db <url>", "Database URL (Local Mode)").action((options) => {
13
+ console.error("\u{1F680} Starting AdminForge AI MCP Server...");
14
+ const env = { ...process.env };
15
+ if (options.config) env.ADMINFORGE_CONFIG_PATH = options.config;
16
+ if (options.db) env.DATABASE_URL = options.db;
17
+ if (options.apiUrl) env.ADMINFORGE_API_URL = options.apiUrl;
18
+ if (options.token) env.ADMINFORGE_TOKEN = options.token;
19
+ const serverPath = path.join(__dirname, "index.js");
20
+ const child = spawn("node", [serverPath], {
21
+ env,
22
+ stdio: ["inherit", "inherit", "inherit"]
23
+ });
24
+ child.on("exit", (code) => {
25
+ process.exit(code || 0);
26
+ });
27
+ });
28
+ program.command("token").description("Generate a scoped Agent Token").requiredOption("-u, --user <id>", "User ID").requiredOption("-r, --role <name>", "User Role").requiredOption("-s, --scopes <list>", "Comma-separated scopes (e.g., posts:create,posts:read)").action((options) => {
29
+ const scopes = options.scopes.split(",").map((s) => s.trim());
30
+ try {
31
+ const token = generateAgentToken(options.user, options.role, scopes);
32
+ console.log("\n\u{1F511} Generated Agent Token:");
33
+ console.log("-----------------------------------------");
34
+ console.log(token);
35
+ console.log("-----------------------------------------");
36
+ console.log("Keep this token secure. It expires in 10 minutes.");
37
+ } catch (error) {
38
+ console.error(`Error: ${error.message}`);
39
+ }
40
+ });
41
+ program.parse();
@@ -0,0 +1,2 @@
1
+
2
+ export { }
package/dist/index.js ADDED
@@ -0,0 +1,283 @@
1
+ import "./chunk-QNQC6QCL.js";
2
+
3
+ // src/index.ts
4
+ import { Server } from "@modelcontextprotocol/sdk/server/index.js";
5
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
6
+ import {
7
+ CallToolRequestSchema,
8
+ ListToolsRequestSchema
9
+ } from "@modelcontextprotocol/sdk/types.js";
10
+ import { createDbClient } from "adminforge";
11
+ import { createController } from "adminforge/next";
12
+ import { verifyAgentToken } from "adminforge/next";
13
+
14
+ // src/orchestrator.ts
15
+ import { z } from "zod";
16
+ var ContentAgent = class {
17
+ constructor(config, db) {
18
+ this.config = config;
19
+ this.db = db;
20
+ }
21
+ config;
22
+ db;
23
+ /**
24
+ * 1. Validate: Deterministic check against Zod schema
25
+ */
26
+ async validate(collectionName, data) {
27
+ const collection = this.getCollection(collectionName);
28
+ const shape = {};
29
+ for (const [name, field] of Object.entries(collection.fields)) {
30
+ shape[name] = field.validation;
31
+ }
32
+ const schema = z.object(shape);
33
+ const result = schema.safeParse(data);
34
+ if (!result.success) {
35
+ return {
36
+ valid: false,
37
+ errors: result.error.errors.map((e) => ({
38
+ path: e.path.join("."),
39
+ message: e.message
40
+ }))
41
+ };
42
+ }
43
+ return { valid: true, data: result.data };
44
+ }
45
+ /**
46
+ * 2. Resolve: Handle relations (names -> IDs)
47
+ */
48
+ async resolveRelations(collectionName, data) {
49
+ const collection = this.getCollection(collectionName);
50
+ const resolvedData = { ...data };
51
+ const unresolved = [];
52
+ for (const [name, field] of Object.entries(collection.fields)) {
53
+ if (field.type === "relation") {
54
+ const val = data[name];
55
+ if (typeof val === "string" && val.length > 0 && !/^[a-z0-9]{25}$/.test(val)) {
56
+ const targetCollection = field.ui.props?.to || field.db.references?.model;
57
+ if (!targetCollection) continue;
58
+ const targetCollectionDef = this.config.collections.find((c) => c.name === targetCollection);
59
+ if (!targetCollectionDef) continue;
60
+ console.error(`[Orchestrator] Resolving relation for ${name}: "${val}"...`);
61
+ const searchFields = ["name", "title", "label"].filter((f) => targetCollectionDef.fields[f]);
62
+ const orQuery = searchFields.map((f) => ({
63
+ [f]: {
64
+ contains: val,
65
+ mode: "insensitive"
66
+ }
67
+ }));
68
+ if (orQuery.length === 0) {
69
+ unresolved.push(name);
70
+ continue;
71
+ }
72
+ const results = await this.db.findMany(targetCollection, {
73
+ where: { OR: orQuery },
74
+ take: 1
75
+ });
76
+ if (results.length > 0) {
77
+ resolvedData[name] = results[0].id;
78
+ } else {
79
+ unresolved.push(name);
80
+ }
81
+ }
82
+ }
83
+ }
84
+ return { resolvedData, unresolved };
85
+ }
86
+ /**
87
+ * 3. Orchestrate: The main loop
88
+ */
89
+ async execute(prompt, collectionName, session) {
90
+ const collection = this.getCollection(collectionName);
91
+ console.error(`[ContentAgent] Orchestrating ${collectionName} for prompt: "${prompt}"`);
92
+ return {
93
+ status: "ready"
94
+ };
95
+ }
96
+ /**
97
+ * Helper to enrich the schema with AI hints for the agent.
98
+ */
99
+ getEnrichedSchema(collectionName) {
100
+ const collection = this.getCollection(collectionName);
101
+ return Object.entries(collection.fields).map(([name, field]) => ({
102
+ name,
103
+ type: field.type,
104
+ required: field.meta?.required ?? false
105
+ }));
106
+ }
107
+ getCollection(name) {
108
+ const collection = this.config.collections.find((c) => c.name === name);
109
+ if (!collection) throw new Error(`Collection ${name} not found`);
110
+ return collection;
111
+ }
112
+ };
113
+
114
+ // src/index.ts
115
+ import path from "path";
116
+ import fs from "fs";
117
+ console.log = (...args) => console.error(...args);
118
+ var CONFIG_PATH_ENV = process.env.ADMINFORGE_CONFIG_PATH;
119
+ async function loadConfig() {
120
+ const cwd = process.cwd();
121
+ const fallbacks = [
122
+ CONFIG_PATH_ENV,
123
+ "/home/yuzaga/Code/AdminForge/apps/example/src/config/adminforge.ts",
124
+ "./apps/example/src/config/adminforge.ts",
125
+ "../../apps/example/src/config/adminforge.ts"
126
+ ].filter(Boolean);
127
+ let resolvedPath = null;
128
+ for (const p of fallbacks) {
129
+ const absolute = path.isAbsolute(p) ? p : path.resolve(cwd, p);
130
+ if (fs.existsSync(absolute)) {
131
+ resolvedPath = absolute;
132
+ break;
133
+ }
134
+ }
135
+ if (!resolvedPath) throw new Error("Could not find adminforge.ts config file.");
136
+ const importPath = path.isAbsolute(resolvedPath) ? `file://${resolvedPath}` : resolvedPath;
137
+ const mod = await import(importPath);
138
+ return { config: mod.config, path: resolvedPath };
139
+ }
140
+ var server = new Server(
141
+ { name: "adminforge-ai", version: "0.3.0" },
142
+ { capabilities: { tools: {} } }
143
+ );
144
+ server.setRequestHandler(ListToolsRequestSchema, async () => {
145
+ return {
146
+ tools: [
147
+ {
148
+ name: "get_form_schema",
149
+ description: "Returns schema + AI hints for a collection. REQUIRES TOKEN.",
150
+ inputSchema: {
151
+ type: "object",
152
+ properties: { collection: { type: "string" }, token: { type: "string" } },
153
+ required: ["collection", "token"]
154
+ }
155
+ },
156
+ {
157
+ name: "list_records",
158
+ description: "Lists records from a collection. REQUIRES TOKEN.",
159
+ inputSchema: {
160
+ type: "object",
161
+ properties: { collection: { type: "string" }, limit: { type: "number" }, token: { type: "string" } },
162
+ required: ["collection", "token"]
163
+ }
164
+ },
165
+ {
166
+ name: "search_records",
167
+ description: "Search records in a collection by keyword. REQUIRES TOKEN.",
168
+ inputSchema: {
169
+ type: "object",
170
+ properties: { collection: { type: "string" }, query: { type: "string" }, token: { type: "string" } },
171
+ required: ["collection", "query", "token"]
172
+ }
173
+ },
174
+ {
175
+ name: "create_record",
176
+ description: "Creates record in AdminForge. REQUIRES TOKEN.",
177
+ inputSchema: {
178
+ type: "object",
179
+ properties: { collection: { type: "string" }, data: { type: "object" }, token: { type: "string" } },
180
+ required: ["collection", "data", "token"]
181
+ }
182
+ },
183
+ {
184
+ name: "update_record",
185
+ description: "Updates an existing record. REQUIRES TOKEN.",
186
+ inputSchema: {
187
+ type: "object",
188
+ properties: { collection: { type: "string" }, id: { type: "string" }, data: { type: "object" }, token: { type: "string" } },
189
+ required: ["collection", "id", "data", "token"]
190
+ }
191
+ },
192
+ {
193
+ name: "delete_record",
194
+ description: "Deletes a record. REQUIRES TOKEN.",
195
+ inputSchema: {
196
+ type: "object",
197
+ properties: { collection: { type: "string" }, id: { type: "string" }, token: { type: "string" } },
198
+ required: ["collection", "id", "token"]
199
+ }
200
+ },
201
+ {
202
+ name: "upload_media",
203
+ description: "Uploads a file (base64) to the media directory. REQUIRES TOKEN.",
204
+ inputSchema: {
205
+ type: "object",
206
+ properties: { filename: { type: "string" }, base64: { type: "string" }, token: { type: "string" } },
207
+ required: ["filename", "base64", "token"]
208
+ }
209
+ }
210
+ ]
211
+ };
212
+ });
213
+ server.setRequestHandler(CallToolRequestSchema, async (request) => {
214
+ const { name, arguments: args } = request.params;
215
+ const token = args.token || process.env.ADMINFORGE_TOKEN;
216
+ if (!token) {
217
+ throw new Error("Unauthorized: Missing token");
218
+ }
219
+ const agentSession = verifyAgentToken(token);
220
+ const { config, path: configPath } = await loadConfig();
221
+ const db = createDbClient(config);
222
+ const agent = new ContentAgent(config, db);
223
+ const securityContext = { agent: agentSession, source: "agent" };
224
+ switch (name) {
225
+ case "get_form_schema": {
226
+ const col = args.collection;
227
+ const fields = agent.getEnrichedSchema(col);
228
+ return { content: [{ type: "text", text: JSON.stringify({ collection: col, fields }, null, 2) }] };
229
+ }
230
+ case "list_records": {
231
+ const col = args.collection;
232
+ const limit = args.limit || 50;
233
+ const results = await db.findMany(col, { take: limit });
234
+ return { content: [{ type: "text", text: JSON.stringify(results, null, 2) }] };
235
+ }
236
+ case "search_records": {
237
+ const col = args.collection;
238
+ const query = args.query;
239
+ const collection = config.collections.find((c) => c.name === col);
240
+ const controller = createController(collection, db, securityContext);
241
+ const results = await controller.list({ search: query });
242
+ return { content: [{ type: "text", text: JSON.stringify(results, null, 2) }] };
243
+ }
244
+ case "create_record": {
245
+ const col = args.collection;
246
+ const collection = config.collections.find((c) => c.name === col);
247
+ const controller = createController(collection, db, securityContext);
248
+ const result = await controller.create(args.data);
249
+ return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] };
250
+ }
251
+ case "update_record": {
252
+ const col = args.collection;
253
+ const id = args.id;
254
+ const collection = config.collections.find((c) => c.name === col);
255
+ const controller = createController(collection, db, securityContext);
256
+ const result = await controller.update(id, args.data);
257
+ return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] };
258
+ }
259
+ case "delete_record": {
260
+ const col = args.collection;
261
+ const id = args.id;
262
+ const collection = config.collections.find((c) => c.name === col);
263
+ const controller = createController(collection, db, securityContext);
264
+ const result = await controller.delete(id);
265
+ return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] };
266
+ }
267
+ case "upload_media": {
268
+ const filename = args.filename;
269
+ const base64 = args.base64;
270
+ const buffer = Buffer.from(base64, "base64");
271
+ const configDir = path.dirname(configPath);
272
+ const uploadDir = path.resolve(configDir, "../../public/uploads");
273
+ if (!fs.existsSync(uploadDir)) fs.mkdirSync(uploadDir, { recursive: true });
274
+ const fullPath = path.join(uploadDir, filename);
275
+ fs.writeFileSync(fullPath, buffer);
276
+ return { content: [{ type: "text", text: JSON.stringify({ url: `/uploads/${filename}`, status: "uploaded" }, null, 2) }] };
277
+ }
278
+ default:
279
+ throw new Error(`Tool ${name} not found`);
280
+ }
281
+ });
282
+ var transport = new StdioServerTransport();
283
+ server.connect(transport).catch(console.error);
package/package.json ADDED
@@ -0,0 +1,35 @@
1
+ {
2
+ "name": "@adminforge/ai",
3
+ "version": "0.2.0",
4
+ "license": "MIT",
5
+ "publishConfig": {
6
+ "access": "public"
7
+ },
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "https://github.com/YuZaGa/AdminForge.git",
11
+ "directory": "packages/ai"
12
+ },
13
+ "type": "module",
14
+ "bin": {
15
+ "adminforge-ai": "./dist/cli.js"
16
+ },
17
+ "dependencies": {
18
+ "@modelcontextprotocol/sdk": "^1.0.1",
19
+ "commander": "^12.1.0",
20
+ "zod": "^3.24.0",
21
+ "adminforge": "0.2.0"
22
+ },
23
+ "devDependencies": {
24
+ "@types/node": "^22.10.1",
25
+ "tsx": "^4.19.2",
26
+ "tsup": "^8.3.5",
27
+ "typescript": "^5.7.2"
28
+ },
29
+ "scripts": {
30
+ "dev": "tsx src/cli.ts",
31
+ "build": "tsup",
32
+ "typecheck": "tsc --noEmit",
33
+ "start": "node dist/cli.js"
34
+ }
35
+ }
package/src/cli.ts ADDED
@@ -0,0 +1,69 @@
1
+ import { Command } from "commander";
2
+ import { generateAgentToken } from "adminforge/next";
3
+ import { spawn } from "child_process";
4
+ import path from "path";
5
+ import fs from "fs";
6
+
7
+ const program = new Command();
8
+
9
+ program
10
+ .name("adminforge-ai")
11
+ .description("CLI to manage AdminForge AI Orchestration and MCP Server")
12
+ .version("0.2.0");
13
+
14
+ /**
15
+ * Command: Start the MCP Server
16
+ */
17
+ program
18
+ .command("start")
19
+ .description("Start the MCP server on stdio")
20
+ .option("-c, --config <path>", "Path to adminforge.ts", "./adminforge.ts")
21
+ .option("-u, --api-url <url>", "Remote AdminForge API URL (Proxy Mode)")
22
+ .option("-t, --token <token>", "Agent Token for Proxy Mode")
23
+ .option("-d, --db <url>", "Database URL (Local Mode)")
24
+ .action((options) => {
25
+ console.error("🚀 Starting AdminForge AI MCP Server...");
26
+
27
+ // Prepare environment
28
+ const env = { ...process.env };
29
+ if (options.config) env.ADMINFORGE_CONFIG_PATH = options.config;
30
+ if (options.db) env.DATABASE_URL = options.db;
31
+ if (options.apiUrl) env.ADMINFORGE_API_URL = options.apiUrl;
32
+ if (options.token) env.ADMINFORGE_TOKEN = options.token;
33
+
34
+ // Run the MCP server process
35
+ const serverPath = path.join(__dirname, "index.js");
36
+ const child = spawn("node", [serverPath], {
37
+ env,
38
+ stdio: ["inherit", "inherit", "inherit"],
39
+ });
40
+
41
+ child.on("exit", (code) => {
42
+ process.exit(code || 0);
43
+ });
44
+ });
45
+
46
+ /**
47
+ * Command: Generate Token
48
+ */
49
+ program
50
+ .command("token")
51
+ .description("Generate a scoped Agent Token")
52
+ .requiredOption("-u, --user <id>", "User ID")
53
+ .requiredOption("-r, --role <name>", "User Role")
54
+ .requiredOption("-s, --scopes <list>", "Comma-separated scopes (e.g., posts:create,posts:read)")
55
+ .action((options) => {
56
+ const scopes = options.scopes.split(",").map((s: string) => s.trim());
57
+ try {
58
+ const token = generateAgentToken(options.user, options.role, scopes);
59
+ console.log("\n🔑 Generated Agent Token:");
60
+ console.log("-----------------------------------------");
61
+ console.log(token);
62
+ console.log("-----------------------------------------");
63
+ console.log("Keep this token secure. It expires in 10 minutes.");
64
+ } catch (error: any) {
65
+ console.error(`Error: ${error.message}`);
66
+ }
67
+ });
68
+
69
+ program.parse();
package/src/index.ts ADDED
@@ -0,0 +1,210 @@
1
+ import { Server } from "@modelcontextprotocol/sdk/server/index.js";
2
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
3
+ import {
4
+ CallToolRequestSchema,
5
+ ListToolsRequestSchema,
6
+ } from "@modelcontextprotocol/sdk/types.js";
7
+ import { createDbClient } from "adminforge";
8
+ import { createController } from "adminforge/next";
9
+ import { verifyAgentToken, type SecurityContext } from "adminforge/next";
10
+ import { ContentAgent } from "./orchestrator.js";
11
+ import path from "path";
12
+ import fs from "fs";
13
+
14
+ // --- GLOBAL STDOUT PROTECTION ---
15
+ console.log = (...args) => console.error(...args);
16
+
17
+ /**
18
+ * --- Configuration & State ---
19
+ */
20
+ const CONFIG_PATH_ENV = process.env.ADMINFORGE_CONFIG_PATH;
21
+ async function loadConfig() {
22
+ const cwd = process.cwd();
23
+ const fallbacks = [
24
+ CONFIG_PATH_ENV,
25
+ "/home/yuzaga/Code/AdminForge/apps/example/src/config/adminforge.ts",
26
+ "./apps/example/src/config/adminforge.ts",
27
+ "../../apps/example/src/config/adminforge.ts",
28
+ ].filter(Boolean) as string[];
29
+
30
+ let resolvedPath: string | null = null;
31
+ for (const p of fallbacks) {
32
+ const absolute = path.isAbsolute(p) ? p : path.resolve(cwd, p);
33
+ if (fs.existsSync(absolute)) {
34
+ resolvedPath = absolute;
35
+ break;
36
+ }
37
+ }
38
+
39
+ if (!resolvedPath) throw new Error("Could not find adminforge.ts config file.");
40
+ const importPath = path.isAbsolute(resolvedPath) ? `file://${resolvedPath}` : resolvedPath;
41
+ const mod = await import(importPath);
42
+ return { config: mod.config, path: resolvedPath };
43
+ }
44
+
45
+ /**
46
+ * --- MCP Server Implementation ---
47
+ */
48
+ const server = new Server(
49
+ { name: "adminforge-ai", version: "0.3.0" },
50
+ { capabilities: { tools: {} } }
51
+ );
52
+
53
+ server.setRequestHandler(ListToolsRequestSchema, async () => {
54
+ return {
55
+ tools: [
56
+ {
57
+ name: "get_form_schema",
58
+ description: "Returns schema + AI hints for a collection. REQUIRES TOKEN.",
59
+ inputSchema: {
60
+ type: "object",
61
+ properties: { collection: { type: "string" }, token: { type: "string" } },
62
+ required: ["collection", "token"],
63
+ },
64
+ },
65
+ {
66
+ name: "list_records",
67
+ description: "Lists records from a collection. REQUIRES TOKEN.",
68
+ inputSchema: {
69
+ type: "object",
70
+ properties: { collection: { type: "string" }, limit: { type: "number" }, token: { type: "string" } },
71
+ required: ["collection", "token"],
72
+ },
73
+ },
74
+ {
75
+ name: "search_records",
76
+ description: "Search records in a collection by keyword. REQUIRES TOKEN.",
77
+ inputSchema: {
78
+ type: "object",
79
+ properties: { collection: { type: "string" }, query: { type: "string" }, token: { type: "string" } },
80
+ required: ["collection", "query", "token"],
81
+ },
82
+ },
83
+ {
84
+ name: "create_record",
85
+ description: "Creates record in AdminForge. REQUIRES TOKEN.",
86
+ inputSchema: {
87
+ type: "object",
88
+ properties: { collection: { type: "string" }, data: { type: "object" }, token: { type: "string" } },
89
+ required: ["collection", "data", "token"],
90
+ },
91
+ },
92
+ {
93
+ name: "update_record",
94
+ description: "Updates an existing record. REQUIRES TOKEN.",
95
+ inputSchema: {
96
+ type: "object",
97
+ properties: { collection: { type: "string" }, id: { type: "string" }, data: { type: "object" }, token: { type: "string" } },
98
+ required: ["collection", "id", "data", "token"],
99
+ },
100
+ },
101
+ {
102
+ name: "delete_record",
103
+ description: "Deletes a record. REQUIRES TOKEN.",
104
+ inputSchema: {
105
+ type: "object",
106
+ properties: { collection: { type: "string" }, id: { type: "string" }, token: { type: "string" } },
107
+ required: ["collection", "id", "token"],
108
+ },
109
+ },
110
+ {
111
+ name: "upload_media",
112
+ description: "Uploads a file (base64) to the media directory. REQUIRES TOKEN.",
113
+ inputSchema: {
114
+ type: "object",
115
+ properties: { filename: { type: "string" }, base64: { type: "string" }, token: { type: "string" } },
116
+ required: ["filename", "base64", "token"],
117
+ },
118
+ },
119
+ ],
120
+ };
121
+ });
122
+
123
+ server.setRequestHandler(CallToolRequestSchema, async (request) => {
124
+ const { name, arguments: args } = request.params;
125
+ const token = (args as any).token || process.env.ADMINFORGE_TOKEN;
126
+
127
+ if (!token) {
128
+ throw new Error("Unauthorized: Missing token");
129
+ }
130
+
131
+ // --- DB TOOLS ---
132
+ const agentSession = verifyAgentToken(token!);
133
+ const { config, path: configPath } = await loadConfig();
134
+ const db = createDbClient(config);
135
+ const agent = new ContentAgent(config, db);
136
+
137
+ const securityContext: SecurityContext = { agent: agentSession, source: "agent" };
138
+
139
+ switch (name) {
140
+ case "get_form_schema": {
141
+ const col = (args as any).collection;
142
+ const fields = agent.getEnrichedSchema(col);
143
+ return { content: [{ type: "text", text: JSON.stringify({ collection: col, fields }, null, 2) }] };
144
+ }
145
+
146
+ case "list_records": {
147
+ const col = (args as any).collection;
148
+ const limit = (args as any).limit || 50;
149
+ const results = await db.findMany(col, { take: limit });
150
+ return { content: [{ type: "text", text: JSON.stringify(results, null, 2) }] };
151
+ }
152
+
153
+ case "search_records": {
154
+ const col = (args as any).collection;
155
+ const query = (args as any).query;
156
+ const collection = config.collections.find((c: any) => c.name === col)!;
157
+ const controller = createController(collection, db, securityContext);
158
+ const results = await controller.list({ search: query });
159
+ return { content: [{ type: "text", text: JSON.stringify(results, null, 2) }] };
160
+ }
161
+
162
+ case "create_record": {
163
+ const col = (args as any).collection;
164
+ const collection = config.collections.find((c: any) => c.name === col)!;
165
+ const controller = createController(collection, db, securityContext);
166
+ const result = await controller.create((args as any).data);
167
+ return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] };
168
+ }
169
+
170
+ case "update_record": {
171
+ const col = (args as any).collection;
172
+ const id = (args as any).id;
173
+ const collection = config.collections.find((c: any) => c.name === col)!;
174
+ const controller = createController(collection, db, securityContext);
175
+ const result = await controller.update(id, (args as any).data);
176
+ return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] };
177
+ }
178
+
179
+ case "delete_record": {
180
+ const col = (args as any).collection;
181
+ const id = (args as any).id;
182
+ const collection = config.collections.find((c: any) => c.name === col)!;
183
+ const controller = createController(collection, db, securityContext);
184
+ const result = await controller.delete(id);
185
+ return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] };
186
+ }
187
+
188
+ case "upload_media": {
189
+ const filename = (args as any).filename;
190
+ const base64 = (args as any).base64;
191
+ const buffer = Buffer.from(base64, "base64");
192
+
193
+ // Resolve upload directory relative to config
194
+ const configDir = path.dirname(configPath);
195
+ const uploadDir = path.resolve(configDir, "../../public/uploads");
196
+
197
+ if (!fs.existsSync(uploadDir)) fs.mkdirSync(uploadDir, { recursive: true });
198
+ const fullPath = path.join(uploadDir, filename);
199
+ fs.writeFileSync(fullPath, buffer);
200
+
201
+ return { content: [{ type: "text", text: JSON.stringify({ url: `/uploads/${filename}`, status: "uploaded" }, null, 2) }] };
202
+ }
203
+
204
+ default:
205
+ throw new Error(`Tool ${name} not found`);
206
+ }
207
+ });
208
+
209
+ const transport = new StdioServerTransport();
210
+ server.connect(transport).catch(console.error);
@@ -0,0 +1,127 @@
1
+ import { type AdminForgeConfig, type CollectionDefinition } from "adminforge";
2
+ import { type DbClient } from "adminforge";
3
+ import { createController } from "adminforge/next";
4
+ import { z } from "zod";
5
+
6
+ /**
7
+ * --- ContentAgent Orchestrator ---
8
+ * A deterministic state machine for AI-assisted content creation.
9
+ */
10
+ export class ContentAgent {
11
+ constructor(
12
+ private config: AdminForgeConfig,
13
+ private db: DbClient
14
+ ) {}
15
+
16
+ /**
17
+ * 1. Validate: Deterministic check against Zod schema
18
+ */
19
+ async validate(collectionName: string, data: Record<string, any>) {
20
+ const collection = this.getCollection(collectionName);
21
+
22
+ // Build validation schema from core field definitions
23
+ const shape: Record<string, z.ZodTypeAny> = {};
24
+ for (const [name, field] of Object.entries(collection.fields)) {
25
+ shape[name] = field.validation;
26
+ }
27
+ const schema = z.object(shape);
28
+
29
+ const result = schema.safeParse(data);
30
+
31
+ if (!result.success) {
32
+ return {
33
+ valid: false,
34
+ errors: result.error.errors.map(e => ({
35
+ path: e.path.join("."),
36
+ message: e.message
37
+ }))
38
+ };
39
+ }
40
+
41
+ return { valid: true, data: result.data };
42
+ }
43
+
44
+ /**
45
+ * 2. Resolve: Handle relations (names -> IDs)
46
+ */
47
+ async resolveRelations(collectionName: string, data: Record<string, any>) {
48
+ const collection = this.getCollection(collectionName);
49
+ const resolvedData = { ...data };
50
+ const unresolved: string[] = [];
51
+
52
+ for (const [name, field] of Object.entries(collection.fields) as [string, any][]) {
53
+ if (field.type === "relation") {
54
+ const val = data[name];
55
+
56
+ // If it's a raw string (not an ID), try to resolve it
57
+ if (typeof val === "string" && val.length > 0 && !/^[a-z0-9]{25}$/.test(val)) {
58
+ const targetCollection = field.ui.props?.to || field.db.references?.model;
59
+ if (!targetCollection) continue;
60
+
61
+ const targetCollectionDef = this.config.collections.find(c => c.name === targetCollection);
62
+ if (!targetCollectionDef) continue;
63
+
64
+ console.error(`[Orchestrator] Resolving relation for ${name}: "${val}"...`);
65
+
66
+ // Build a safe query based on known common search fields
67
+ const searchFields = ["name", "title", "label"].filter(f => targetCollectionDef.fields[f]);
68
+ const orQuery = searchFields.map(f => ({
69
+ [f]: {
70
+ contains: val,
71
+ mode: "insensitive"
72
+ }
73
+ }));
74
+
75
+ if (orQuery.length === 0) {
76
+ unresolved.push(name);
77
+ continue;
78
+ }
79
+
80
+ const results = await this.db.findMany(targetCollection, {
81
+ where: { OR: orQuery },
82
+ take: 1,
83
+ });
84
+
85
+ if (results.length > 0) {
86
+ resolvedData[name] = (results[0] as any).id;
87
+ } else {
88
+ unresolved.push(name);
89
+ }
90
+ }
91
+ }
92
+ }
93
+
94
+ return { resolvedData, unresolved };
95
+ }
96
+
97
+ /**
98
+ * 3. Orchestrate: The main loop
99
+ */
100
+ async execute(prompt: string, collectionName: string, session: any) {
101
+ const collection = this.getCollection(collectionName);
102
+ console.error(`[ContentAgent] Orchestrating ${collectionName} for prompt: "${prompt}"`);
103
+
104
+ return {
105
+ status: "ready"
106
+ };
107
+ }
108
+
109
+ /**
110
+ * Helper to enrich the schema with AI hints for the agent.
111
+ */
112
+ getEnrichedSchema(collectionName: string) {
113
+ const collection = this.getCollection(collectionName);
114
+
115
+ return Object.entries(collection.fields).map(([name, field]: [string, any]) => ({
116
+ name,
117
+ type: field.type,
118
+ required: field.meta?.required ?? false,
119
+ }));
120
+ }
121
+
122
+ private getCollection(name: string): CollectionDefinition {
123
+ const collection = this.config.collections.find((c) => c.name === name);
124
+ if (!collection) throw new Error(`Collection ${name} not found`);
125
+ return collection;
126
+ }
127
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,9 @@
1
+ {
2
+ "extends": "../../tsconfig.json",
3
+ "compilerOptions": {
4
+ "outDir": "./dist",
5
+ "rootDir": "./src",
6
+ "types": ["node"]
7
+ },
8
+ "include": ["src"]
9
+ }
package/tsup.config.ts ADDED
@@ -0,0 +1,11 @@
1
+ import { defineConfig } from "tsup";
2
+
3
+ export default defineConfig({
4
+ entry: ["src/index.ts", "src/cli.ts"],
5
+ format: ["esm"],
6
+ dts: true,
7
+ clean: true,
8
+ shims: true,
9
+ outDir: "dist",
10
+ target: "es2022",
11
+ });