@adminforth/agent 3.1.10 → 3.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/README.md +71 -38
  2. package/dist/application/ports.d.ts +3 -1
  3. package/dist/application/runTurnUseCase.d.ts +3 -3
  4. package/dist/application/runTurnUseCase.js +8 -6
  5. package/dist/custom/ChatSurface.vue +25 -8
  6. package/dist/custom/{skills/charts/SKILL.md → charts.md} +2 -4
  7. package/dist/custom/composables/useAgentStore.ts +0 -20
  8. package/dist/custom/composables/useAgentTransitions.ts +13 -37
  9. package/dist/custom/utils.ts +5 -0
  10. package/dist/domain/systemPrompt.d.ts +3 -2
  11. package/dist/domain/systemPrompt.js +14 -53
  12. package/dist/index.d.ts +0 -3
  13. package/dist/index.js +24 -35
  14. package/dist/llm/agentRuntime.d.ts +9 -8
  15. package/dist/llm/agentRuntime.js +134 -106
  16. package/dist/llm/langGraphLlm.d.ts +3 -0
  17. package/dist/llm/langGraphLlm.js +10 -2
  18. package/dist/llm/middleware/mcpToolsMiddleware.d.ts +7 -0
  19. package/dist/llm/middleware/{apiToolsMiddleware.js → mcpToolsMiddleware.js} +16 -36
  20. package/dist/tools/agentToolProvider.d.ts +16 -5
  21. package/dist/tools/agentToolProvider.js +26 -10
  22. package/dist/tools/fetchToolSchema.d.ts +7 -3
  23. package/dist/tools/fetchToolSchema.js +29 -22
  24. package/dist/tools/mcpConnection.d.ts +38 -0
  25. package/dist/tools/mcpConnection.js +42 -0
  26. package/dist/tools/mcpTool.d.ts +3 -0
  27. package/dist/tools/{apiTool.js → mcpTool.js} +7 -23
  28. package/dist/tools/toolLabels.d.ts +5 -0
  29. package/dist/tools/toolLabels.js +49 -0
  30. package/dist/transport/http/context.d.ts +2 -2
  31. package/dist/transport/http/sessionEndpoints.js +1 -1
  32. package/package.json +6 -4
  33. package/dist/custom/skills/analyze_data/SKILL.md +0 -25
  34. package/dist/custom/skills/fetch_data/SKILL.md +0 -31
  35. package/dist/custom/skills/mutate_data/SKILL.md +0 -121
  36. package/dist/llm/middleware/apiToolsMiddleware.d.ts +0 -3
  37. package/dist/tools/apiBasedTools.d.ts +0 -30
  38. package/dist/tools/apiBasedTools.js +0 -488
  39. package/dist/tools/apiTool.d.ts +0 -6
  40. package/dist/tools/fetchSkill.d.ts +0 -8
  41. package/dist/tools/fetchSkill.js +0 -51
  42. package/dist/tools/index.d.ts +0 -4
  43. package/dist/tools/index.js +0 -32
  44. package/dist/tools/skills/registry.d.ts +0 -11
  45. package/dist/tools/skills/registry.js +0 -107
@@ -11,12 +11,10 @@ import { ToolMessage } from "@langchain/core/messages";
11
11
  import { isGraphInterrupt } from "@langchain/langgraph";
12
12
  import { createMiddleware } from "langchain";
13
13
  import { logger } from "adminforth";
14
- import { formatApiBasedToolCall, } from "../../tools/apiBasedTools.js";
14
+ import { formatToolCall } from "../../tools/toolLabels.js";
15
15
  import { createToolCallTracker, } from "../../domain/toolCallEvents.js";
16
- import { ALWAYS_AVAILABLE_API_TOOL_NAMES } from "../../tools/index.js";
17
- import { createApiTool } from "../../tools/apiTool.js";
18
16
  import { isAbortError } from "../../shared/errors.js";
19
- function getEnabledApiToolNames(messages) {
17
+ function getEnabledToolNames(messages) {
20
18
  const enabledToolNames = new Set();
21
19
  for (const message of messages) {
22
20
  if (!ToolMessage.isInstance(message) || message.name !== "fetch_tool_schema") {
@@ -43,22 +41,20 @@ function getEnabledApiToolNames(messages) {
43
41
  }
44
42
  return enabledToolNames;
45
43
  }
46
- export function createApiBasedToolsMiddleware(apiBasedTools, adminforth) {
47
- const alwaysAvailableApiToolNames = new Set(ALWAYS_AVAILABLE_API_TOOL_NAMES);
48
- const dynamicTools = Object.fromEntries(Object.entries(apiBasedTools).map(([toolName, apiBasedTool]) => [
49
- toolName,
50
- createApiTool(toolName, apiBasedTool),
51
- ]));
44
+ /**
45
+ * Adds the MCP tools loaded with fetch_tool_schema to the next model calls, routes their calls,
46
+ * and reports every tool call to the processing timeline.
47
+ */
48
+ export function createMcpToolsMiddleware(dynamicTools, adminforth) {
49
+ const loadedDynamicToolNames = (messages) => [...getEnabledToolNames(messages)].filter((toolName) => toolName in dynamicTools);
52
50
  return createMiddleware({
53
- name: "ApiBasedToolsMiddleware",
51
+ name: "McpToolsMiddleware",
54
52
  wrapModelCall(request, handler) {
55
53
  return __awaiter(this, void 0, void 0, function* () {
56
- const enabledApiToolNames = getEnabledApiToolNames(request.state.messages);
57
- const tools = [...enabledApiToolNames]
58
- .filter((toolName) => !alwaysAvailableApiToolNames.has(toolName))
59
- .map((toolName) => dynamicTools[toolName]);
60
- const availableTools = [...request.tools, ...tools];
61
- return handler(Object.assign(Object.assign({}, request), { tools: availableTools }));
54
+ return handler(Object.assign(Object.assign({}, request), { tools: [
55
+ ...request.tools,
56
+ ...loadedDynamicToolNames(request.state.messages).map((toolName) => dynamicTools[toolName]),
57
+ ] }));
62
58
  });
63
59
  },
64
60
  wrapToolCall(request, handler) {
@@ -69,7 +65,7 @@ export function createApiBasedToolsMiddleware(apiBasedTools, adminforth) {
69
65
  throw new Error(`Tool call "${request.toolCall.name}" has no id.`);
70
66
  }
71
67
  const toolCallId = request.toolCall.id;
72
- const { adminUser, abortSignal, emit, sequenceDebugSink, userTimeZone } = request.runtime.context;
68
+ const { abortSignal, emit, sequenceDebugSink } = request.runtime.context;
73
69
  const emitToolCall = (event) => {
74
70
  sequenceDebugSink.handleToolCallEvent(event);
75
71
  void (emit === null || emit === void 0 ? void 0 : emit({
@@ -78,33 +74,17 @@ export function createApiBasedToolsMiddleware(apiBasedTools, adminforth) {
78
74
  }));
79
75
  };
80
76
  const toolArgs = ((_a = request.toolCall.args) !== null && _a !== void 0 ? _a : {});
81
- let toolInfo;
82
- if (request.toolCall.name === "fetch_skill") {
83
- toolInfo = `Load ${toolArgs.skillName.split("_").join(" ")} skill`;
84
- }
85
- else if (request.toolCall.name === "fetch_tool_schema") {
86
- toolInfo = `Load ${toolArgs.toolName.split("_").join(" ")} tool `;
87
- }
88
- else {
89
- toolInfo = yield formatApiBasedToolCall({
90
- adminforth,
91
- adminUser,
92
- inputs: toolArgs,
93
- toolName: request.toolCall.name,
94
- userTimeZone,
95
- });
96
- }
97
77
  const toolCallTracker = createToolCallTracker({
98
78
  emit: emitToolCall,
99
79
  toolCallId,
100
80
  toolName: request.toolCall.name,
101
- toolInfo,
81
+ toolInfo: formatToolCall(adminforth, request.toolCall.name, toolArgs),
102
82
  input: toolArgs,
103
83
  startedAt,
104
84
  });
105
85
  toolCallTracker.start();
106
86
  try {
107
- const result = getEnabledApiToolNames(request.state.messages).has(request.toolCall.name)
87
+ const result = loadedDynamicToolNames(request.state.messages).includes(request.toolCall.name)
108
88
  ? yield handler(Object.assign(Object.assign({}, request), { tool: dynamicTools[request.toolCall.name] }))
109
89
  : yield handler(request);
110
90
  toolCallTracker.finishSuccess(result);
@@ -1,9 +1,20 @@
1
1
  import type { IAdminForth } from "adminforth";
2
- import type { ApiBasedTool } from "./apiBasedTools.js";
2
+ import type { ClientTool } from "@langchain/core/tools";
3
+ import { type McpConnectionInput } from "./mcpConnection.js";
4
+ /** The tools of one agent turn, backed by one MCP connection that `close` ends. */
5
+ export type AgentToolSet = {
6
+ /** MCP server instructions, sent ahead of the agent's own system prompt. */
7
+ instructions: string;
8
+ /** Tools the model can call from the first step. */
9
+ baseTools: ClientTool[];
10
+ /** MCP tools the model loads on demand with fetch_tool_schema, by name. */
11
+ dynamicTools: Record<string, ClientTool>;
12
+ /** Tools that pause for the user's approval before they run. */
13
+ approvalToolNames: string[];
14
+ close(): Promise<void>;
15
+ };
3
16
  export declare class AgentToolProvider {
4
17
  private readonly getAdminforth;
5
- private readonly getInternalAgentResourceIds;
6
- constructor(getAdminforth: () => IAdminForth, getInternalAgentResourceIds: () => string[]);
7
- getApiBasedTools(): Record<string, ApiBasedTool>;
8
- getTools(apiBasedTools: Record<string, ApiBasedTool>): Promise<import("@langchain/core/tools").ClientTool[]>;
18
+ constructor(getAdminforth: () => IAdminForth);
19
+ open(input: Omit<McpConnectionInput, "requestUrl">): Promise<AgentToolSet>;
9
20
  }
@@ -7,21 +7,37 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
7
7
  step((generator = generator.apply(thisArg, _arguments || [])).next());
8
8
  });
9
9
  };
10
- import { prepareApiBasedTools } from "./apiBasedTools.js";
11
- import { createAgentTools } from "./index.js";
10
+ import { connectMcp, MCP_PLUGIN_CLASS_NAME } from "./mcpConnection.js";
11
+ import { createMcpTool } from "./mcpTool.js";
12
+ import { createFetchToolSchemaTool } from "./fetchToolSchema.js";
13
+ import { createGetUserLocationTool } from "./getUserLocation.js";
14
+ import { createNavigateUserTool } from "./navigateUser.js";
15
+ // MCP tools the model can call from the first step; it loads the others with fetch_tool_schema.
16
+ const BASE_MCP_TOOL_NAMES = new Set(["fetch_skill", "get_resources_list", "get_resource", "wait_for_confirmation"]);
12
17
  export class AgentToolProvider {
13
- constructor(getAdminforth, getInternalAgentResourceIds) {
18
+ constructor(getAdminforth) {
14
19
  this.getAdminforth = getAdminforth;
15
- this.getInternalAgentResourceIds = getInternalAgentResourceIds;
16
20
  }
17
- getApiBasedTools() {
18
- return prepareApiBasedTools(this.getAdminforth(), this.getInternalAgentResourceIds());
19
- }
20
- getTools(apiBasedTools) {
21
+ open(input) {
21
22
  return __awaiter(this, void 0, void 0, function* () {
22
- var _a;
23
23
  const adminforth = this.getAdminforth();
24
- return createAgentTools((_a = adminforth.config.customization.customComponentsDir) !== null && _a !== void 0 ? _a : "custom", apiBasedTools, adminforth.activatedPlugins.map((plugin) => plugin.customFolderPath));
24
+ const connection = yield connectMcp(adminforth.getPluginByClassName(MCP_PLUGIN_CLASS_NAME), Object.assign(Object.assign({}, input), { requestUrl: adminforth.config.baseUrlSlashed }));
25
+ const baseMcpTools = connection.tools.filter((mcpTool) => BASE_MCP_TOOL_NAMES.has(mcpTool.name));
26
+ const dynamicMcpTools = connection.tools.filter((mcpTool) => !BASE_MCP_TOOL_NAMES.has(mcpTool.name));
27
+ return {
28
+ instructions: connection.instructions,
29
+ baseTools: [
30
+ ...baseMcpTools.map((mcpTool) => createMcpTool(mcpTool, connection)),
31
+ createGetUserLocationTool(),
32
+ createNavigateUserTool(),
33
+ createFetchToolSchemaTool(connection.tools, dynamicMcpTools),
34
+ ],
35
+ dynamicTools: Object.fromEntries(dynamicMcpTools.map((mcpTool) => [mcpTool.name, createMcpTool(mcpTool, connection)])),
36
+ approvalToolNames: connection.tools
37
+ .filter((mcpTool) => { var _a; return (_a = mcpTool.annotations) === null || _a === void 0 ? void 0 : _a.destructiveHint; })
38
+ .map((mcpTool) => mcpTool.name),
39
+ close: connection.close,
40
+ };
25
41
  });
26
42
  }
27
43
  }
@@ -1,9 +1,13 @@
1
+ import type { Tool } from "@modelcontextprotocol/client";
1
2
  import { z } from "zod";
2
- import type { ApiBasedTool } from "./apiBasedTools.js";
3
- export declare function createFetchToolSchemaTool(apiBasedTools: Record<string, ApiBasedTool>): Promise<import("langchain").DynamicStructuredTool<z.ZodObject<{
3
+ /**
4
+ * Loads an MCP tool for later steps: the tools middleware adds every tool this returned status 200 for.
5
+ * Like MCP clients that load tool schemas on demand, its description names every tool it can load.
6
+ */
7
+ export declare function createFetchToolSchemaTool(mcpTools: Tool[], loadableTools: Tool[]): import("langchain").DynamicStructuredTool<z.ZodObject<{
4
8
  toolName: z.ZodString;
5
9
  }, z.core.$strip>, {
6
10
  toolName: string;
7
11
  }, {
8
12
  toolName: string;
9
- }, string, unknown, "fetch_tool_schema">>;
13
+ }, string, unknown, "fetch_tool_schema">;
@@ -9,31 +9,38 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
9
9
  };
10
10
  import { tool } from "langchain";
11
11
  import { z } from "zod";
12
+ // The catalog shows the first sentence of each tool description; the full one comes with the loaded tool.
13
+ const FIRST_SENTENCE_RE = /^[\s\S]*?[.!?](?=\s|$)/;
14
+ const WHITESPACE_RE = /\s+/g;
12
15
  const fetchToolSchemaSchema = z.object({
13
16
  toolName: z
14
17
  .string()
15
- .describe("Name of the API-based tool to load, for example get_resource."),
18
+ .describe("Name of the admin panel tool to load, for example create_record."),
16
19
  });
17
- export function createFetchToolSchemaTool(apiBasedTools) {
18
- return __awaiter(this, void 0, void 0, function* () {
19
- return tool((_a) => __awaiter(this, [_a], void 0, function* ({ toolName }) {
20
- const toolDefinition = apiBasedTools[toolName];
21
- if (!toolDefinition) {
22
- return JSON.stringify({
23
- status: 404,
24
- error: "TOOL_NOT_FOUND",
25
- message: `Tool "${toolName}" not found.`,
26
- }, null, 2);
27
- }
28
- return JSON.stringify({
29
- status: 200,
30
- name: toolName,
31
- loaded: true,
32
- }, null, 2);
33
- }), {
34
- name: "fetch_tool_schema",
35
- description: "Fetch the schema for an API-based AdminForth tool by name and load it for later use. Use this right after fetch_skill when the skill mentions non-base tools.",
36
- schema: fetchToolSchemaSchema,
37
- });
20
+ function catalogEntry({ name, description }) {
21
+ var _a, _b;
22
+ if (!description)
23
+ return `- ${name}`;
24
+ const summary = ((_b = (_a = description.match(FIRST_SENTENCE_RE)) === null || _a === void 0 ? void 0 : _a[0]) !== null && _b !== void 0 ? _b : description).replace(WHITESPACE_RE, " ");
25
+ return `- ${name}: ${summary}`;
26
+ }
27
+ /**
28
+ * Loads an MCP tool for later steps: the tools middleware adds every tool this returned status 200 for.
29
+ * Like MCP clients that load tool schemas on demand, its description names every tool it can load.
30
+ */
31
+ export function createFetchToolSchemaTool(mcpTools, loadableTools) {
32
+ const mcpToolNames = new Set(mcpTools.map((mcpTool) => mcpTool.name));
33
+ return tool((_a) => __awaiter(this, [_a], void 0, function* ({ toolName }) {
34
+ return JSON.stringify(mcpToolNames.has(toolName)
35
+ ? { status: 200, name: toolName, loaded: true }
36
+ : { status: 404, error: "TOOL_NOT_FOUND", message: `Tool "${toolName}" not found.` }, null, 2);
37
+ }), {
38
+ name: "fetch_tool_schema",
39
+ description: [
40
+ "Loads an admin panel tool so you can call it from the next step. Load a tool before its first call, right after fetch_skill when the skill lists tools you cannot call yet.",
41
+ "Tools you can load:",
42
+ ...loadableTools.map(catalogEntry),
43
+ ].join("\n"),
44
+ schema: fetchToolSchemaSchema,
38
45
  });
39
46
  }
@@ -0,0 +1,38 @@
1
+ import { type Tool, type Transport } from "@modelcontextprotocol/client";
2
+ import type { AdminUser } from "adminforth";
3
+ export declare const MCP_PLUGIN_CLASS_NAME = "AdminForthMcpPlugin";
4
+ /** The `openConnection` session of @adminforth/mcp: a user this process already authenticated. */
5
+ type McpSession = {
6
+ adminUser: AdminUser;
7
+ /** Binds 2FA confirmations of the connection's actions to it. */
8
+ connection: {
9
+ id: string;
10
+ name: string;
11
+ };
12
+ readOnly: boolean;
13
+ headers: Record<string, string>;
14
+ requestUrl: string;
15
+ timeZone?: string;
16
+ };
17
+ /** The part of the @adminforth/mcp plugin the agent works through. */
18
+ export type McpPlugin = {
19
+ openConnection(session: McpSession): Promise<Transport>;
20
+ };
21
+ export type McpConnectionInput = {
22
+ adminUser: AdminUser;
23
+ sessionId: string;
24
+ userTimeZone?: string;
25
+ requestUrl: string;
26
+ };
27
+ /** One MCP connection of an agent turn, open until `close`. */
28
+ export type AgentMcpConnection = {
29
+ /** Server instructions: rules for every MCP client and the list of skills. */
30
+ instructions: string;
31
+ tools: Tool[];
32
+ /** Calls a tool and returns its YAML output; tool-level errors come back as output too. */
33
+ callTool(name: string, args: Record<string, unknown>, signal?: AbortSignal): Promise<string>;
34
+ close(): Promise<void>;
35
+ };
36
+ /** The agent has exactly the permissions of the user it runs for, so its connections are never read-only. */
37
+ export declare function connectMcp(mcp: McpPlugin, input: McpConnectionInput): Promise<AgentMcpConnection>;
38
+ export {};
@@ -0,0 +1,42 @@
1
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
+ return new (P || (P = Promise))(function (resolve, reject) {
4
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
8
+ });
9
+ };
10
+ import { Client } from "@modelcontextprotocol/client";
11
+ export const MCP_PLUGIN_CLASS_NAME = "AdminForthMcpPlugin";
12
+ // Shown in the audit log and on the 2FA confirmation page of the admin panel.
13
+ const AGENT_EXECUTED_BY = "af-agent";
14
+ const AGENT_CONNECTION_NAME = "AdminForth Agent";
15
+ const AGENT_CLIENT_INFO = { name: "adminforth-agent", version: "1.0.0" };
16
+ /** The agent has exactly the permissions of the user it runs for, so its connections are never read-only. */
17
+ export function connectMcp(mcp, input) {
18
+ return __awaiter(this, void 0, void 0, function* () {
19
+ const client = new Client(AGENT_CLIENT_INFO);
20
+ yield client.connect(yield mcp.openConnection({
21
+ adminUser: Object.assign(Object.assign({}, input.adminUser), { executedBy: AGENT_EXECUTED_BY }),
22
+ connection: { id: `agent:${input.sessionId}`, name: AGENT_CONNECTION_NAME },
23
+ readOnly: false,
24
+ headers: {},
25
+ requestUrl: input.requestUrl,
26
+ timeZone: input.userTimeZone,
27
+ }));
28
+ const { tools } = yield client.listTools();
29
+ return {
30
+ instructions: client.getInstructions(),
31
+ tools,
32
+ callTool(name, args, signal) {
33
+ return __awaiter(this, void 0, void 0, function* () {
34
+ // The AdminForth MCP server answers every call with a single text block.
35
+ const { content } = yield client.callTool({ name, arguments: args }, { signal });
36
+ return content[0].text;
37
+ });
38
+ },
39
+ close: () => client.close(),
40
+ };
41
+ });
42
+ }
@@ -0,0 +1,3 @@
1
+ import type { Tool } from "@modelcontextprotocol/client";
2
+ import type { AgentMcpConnection } from "./mcpConnection.js";
3
+ export declare function createMcpTool(mcpTool: Tool, connection: AgentMcpConnection): import("langchain").DynamicStructuredTool<Record<string, unknown>, unknown, unknown, string, unknown, string>;
@@ -8,19 +8,9 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
8
8
  });
9
9
  };
10
10
  import { tool } from "langchain";
11
- const emptyToolSchema = {
12
- type: "object",
13
- properties: {},
14
- additionalProperties: true,
15
- };
11
+ // Model providers reject top-level composite keywords in tool schemas; the MCP server still validates them.
16
12
  function normalizeToolInputSchema(inputSchema) {
17
- if (!inputSchema || typeof inputSchema !== "object" || Array.isArray(inputSchema)) {
18
- return emptyToolSchema;
19
- }
20
- const schema = JSON.parse(JSON.stringify(inputSchema));
21
- if (schema.type !== "object") {
22
- return emptyToolSchema;
23
- }
13
+ const schema = structuredClone(inputSchema);
24
14
  const notes = [];
25
15
  if ("if" in schema || "then" in schema || "else" in schema || "allOf" in schema) {
26
16
  delete schema.if;
@@ -43,20 +33,14 @@ function normalizeToolInputSchema(inputSchema) {
43
33
  }
44
34
  return schema;
45
35
  }
46
- export function createApiTool(toolName, apiBasedTool) {
36
+ export function createMcpTool(mcpTool, connection) {
47
37
  var _a;
48
38
  return tool((input, runtime) => __awaiter(this, void 0, void 0, function* () {
49
- const normalizedInput = (input !== null && input !== void 0 ? input : {});
50
- return apiBasedTool.call({
51
- adminUser: runtime.context.adminUser,
52
- abortSignal: runtime.context.abortSignal,
53
- inputs: normalizedInput,
54
- userTimeZone: runtime.context.userTimeZone,
55
- });
39
+ return connection.callTool(mcpTool.name, input, runtime.context.abortSignal);
56
40
  }), {
57
- name: toolName,
58
- description: (_a = apiBasedTool.description) !== null && _a !== void 0 ? _a : `${toolName} tool`,
59
- schema: normalizeToolInputSchema(apiBasedTool.input_schema),
41
+ name: mcpTool.name,
42
+ description: (_a = mcpTool.description) !== null && _a !== void 0 ? _a : mcpTool.name,
43
+ schema: normalizeToolInputSchema(mcpTool.inputSchema),
60
44
  verboseParsingErrors: true,
61
45
  });
62
46
  }
@@ -0,0 +1,5 @@
1
+ import type { IAdminForth } from "adminforth";
2
+ type ToolInputs = Record<string, unknown>;
3
+ /** Human-readable label of a tool call for the processing timeline; undefined for tools without one. */
4
+ export declare function formatToolCall(adminforth: IAdminForth, toolName: string, inputs: ToolInputs): string;
5
+ export {};
@@ -0,0 +1,49 @@
1
+ function getInputString(inputs, key) {
2
+ const value = inputs[key];
3
+ return typeof value === "string" && value ? value : undefined;
4
+ }
5
+ function getInputArrayLength(inputs, key) {
6
+ const value = inputs[key];
7
+ return Array.isArray(value) ? value.length : undefined;
8
+ }
9
+ function resourceLabel(adminforth, inputs) {
10
+ var _a, _b;
11
+ const resourceId = getInputString(inputs, "resourceId");
12
+ const resource = adminforth.config.resources.find((res) => res.resourceId === resourceId);
13
+ return (_b = (_a = resource === null || resource === void 0 ? void 0 : resource.label) !== null && _a !== void 0 ? _a : resourceId) !== null && _b !== void 0 ? _b : "resource";
14
+ }
15
+ function getDataPrefix(inputs) {
16
+ const offset = typeof inputs.offset === "number" ? inputs.offset : undefined;
17
+ const limit = typeof inputs.limit === "number" ? inputs.limit : undefined;
18
+ if (offset !== undefined && limit !== undefined) {
19
+ return `${offset}-${offset + limit} `;
20
+ }
21
+ return limit === undefined ? "" : `${limit} `;
22
+ }
23
+ function actionText(inputs) {
24
+ const actionId = getInputString(inputs, "actionId");
25
+ return actionId ? ` action ${actionId}` : " action";
26
+ }
27
+ function bulkActionLabel({ inputs, resourceLabel }) {
28
+ const recordCount = getInputArrayLength(inputs, "recordIds");
29
+ const recordsText = recordCount === undefined ? "" : ` for ${recordCount} records`;
30
+ return `Run ${resourceLabel}${actionText(inputs)}${recordsText}`;
31
+ }
32
+ const TOOL_LABELS = {
33
+ fetch_skill: ({ inputs }) => `Load ${inputs.skillName.split("-").join(" ")} skill`,
34
+ fetch_tool_schema: ({ inputs }) => `Load ${inputs.toolName.split("_").join(" ")} tool`,
35
+ get_resource: ({ resourceLabel }) => `Get ${resourceLabel} resource`,
36
+ get_resource_data: ({ inputs, resourceLabel }) => `Get ${getDataPrefix(inputs)}${resourceLabel}`,
37
+ aggregate: ({ resourceLabel }) => `Aggregate ${resourceLabel}`,
38
+ start_custom_action: ({ inputs, resourceLabel }) => `Run ${resourceLabel}${actionText(inputs)}`,
39
+ start_custom_bulk_action: bulkActionLabel,
40
+ start_bulk_action: bulkActionLabel,
41
+ create_record: ({ resourceLabel }) => `Create ${resourceLabel}`,
42
+ update_record: ({ resourceLabel }) => `Update ${resourceLabel}`,
43
+ delete_record: ({ resourceLabel }) => `Delete ${resourceLabel}`,
44
+ };
45
+ /** Human-readable label of a tool call for the processing timeline; undefined for tools without one. */
46
+ export function formatToolCall(adminforth, toolName, inputs) {
47
+ var _a;
48
+ return (_a = TOOL_LABELS[toolName]) === null || _a === void 0 ? void 0 : _a.call(TOOL_LABELS, { inputs, resourceLabel: resourceLabel(adminforth, inputs) });
49
+ }
@@ -1,4 +1,4 @@
1
- import type { ChatSurfaceAdapter, ChatSurfaceEventSink, ChatSurfaceIncomingMessage, IAdminForth, IAdminForthEndpointHandlerInput } from "adminforth";
1
+ import type { AdminUser, ChatSurfaceAdapter, ChatSurfaceEventSink, ChatSurfaceIncomingMessage, IAdminForth, IAdminForthEndpointHandlerInput } from "adminforth";
2
2
  import type { HandleEditTurnInput, HandleSpeechTurnInput, HandleTurnInput, RunAndPersistAgentResponseInput, RunAndPersistAgentResponseResult } from "../../domain/turnTypes.js";
3
3
  import type { PluginOptions } from "../../types.js";
4
4
  import type { ApprovalDescription } from "../../tools/approvalFormatter.js";
@@ -23,7 +23,7 @@ export type AgentEndpointsContext = {
23
23
  }>;
24
24
  runAndPersistAgentResponse(input: RunAndPersistAgentResponseInput): Promise<RunAndPersistAgentResponseResult>;
25
25
  getSessionTurns(sessionId: string): Promise<SessionTurn[]>;
26
- getPendingApprovals(sessionId: string): Promise<ApprovalDescription[]>;
26
+ getPendingApprovals(sessionId: string, adminUser: AdminUser): Promise<ApprovalDescription[]>;
27
27
  createNewTurn(sessionId: string, prompt: string, response?: string): Promise<string>;
28
28
  createSystemTurn(sessionId: string, systemMessage: string): Promise<string>;
29
29
  appendSteerToCurrentTurn(sessionId: string, steerText: string): Promise<void>;
@@ -83,7 +83,7 @@ export function setupSessionEndpoints(ctx, server) {
83
83
  ctx.getSessionTurns(sessionId),
84
84
  // The approval prompt lives only in the browser, so a reload has to rebuild it
85
85
  // from the agent's persisted state — otherwise the user cannot answer it.
86
- ctx.getPendingApprovals(sessionId),
86
+ ctx.getPendingApprovals(sessionId, adminUser),
87
87
  ]);
88
88
  return {
89
89
  session: {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@adminforth/agent",
3
- "version": "3.1.10",
3
+ "version": "3.3.0",
4
4
  "main": "dist/index.js",
5
5
  "types": "dist/index.d.ts",
6
6
  "type": "module",
@@ -34,9 +34,10 @@
34
34
  "license": "MIT",
35
35
  "description": "AI agent plugin for AdminForth with tool-based workflows and persistent chat sessions",
36
36
  "devDependencies": {
37
+ "@modelcontextprotocol/server": "2.3.1",
37
38
  "@types/jest": "^30.0.0",
38
39
  "@types/node": "latest",
39
- "adminforth": "^4.7.3",
40
+ "adminforth": "^4.14.0",
40
41
  "jest": "^30.3.0",
41
42
  "semantic-release": "^24.2.1",
42
43
  "semantic-release-slack-bot": "^4.0.2",
@@ -47,7 +48,7 @@
47
48
  "@langchain/core": "1.2.5",
48
49
  "@langchain/langgraph": "1.2.8",
49
50
  "@langchain/langgraph-checkpoint": "1.0.1",
50
- "dayjs": "^1.11.20",
51
+ "@modelcontextprotocol/client": "2.3.1",
51
52
  "langchain": "1.3.3",
52
53
  "multer": "^2.1.1",
53
54
  "vue-i18n": "^11.4.0",
@@ -80,6 +81,7 @@
80
81
  }
81
82
  ],
82
83
  "peerDependencies": {
83
- "adminforth": "^4.7.3"
84
+ "adminforth": "^4.7.3",
85
+ "@adminforth/mcp": "^3.2.0"
84
86
  }
85
87
  }
@@ -1,25 +0,0 @@
1
- name: analyze_data
2
- description: Universal skill to analyze AdminForth resource data, summarize trends, and compare distributions from fetched rows.
3
- ---
4
-
5
- # Involved tools
6
-
7
- Always call `get_resource` first if you need to inspect resource structure and column names.
8
-
9
- Then you need to select between two main tools for fetching data:
10
-
11
- - Load and call `aggregate` tool to fetch data for analytics. This is the main tool for fast server-side aggregations, including filtered data, grouped metrics, and date buckets such as day, week, or month. Always prioritize this way of fetching data for analytics, as it is optimized for performance and reduces the amount of data transferred and processed in-memory.
12
-
13
- - Load and call `get_resource_data` tool only when the requested analysis cannot be answered with `aggregate`. When using it, pass `columns` with only the fields required for the calculation so large result sets do not include unrelated row data.
14
-
15
- # Instructions
16
-
17
- When the user asks for analytics, reports, trends, comparisons, or distributions:
18
-
19
- - Fetch the requested data using `aggregate` whenever possible.
20
- - If it is not possible to get the required aggregates using `aggregate`, fetch the underlying rows with `get_resource_data`.
21
- - Prefer narrow requests: use filters, sorting, pagination, and date ranges whenever possible.
22
- - Prefer narrow row payloads: include `columns` when only one or a few fields are needed.
23
- - If the request is ambiguous, clarify the resource, metric, grouping, or date range before fetching data.
24
- - Return a short written summary with the key finding and most important numbers.
25
- - If the user asks for a chart, or if a chart would help and you decide to produce one, invoke the `charts` skill for chart formatting and Vega-Lite requirements.
@@ -1,31 +0,0 @@
1
- name: fetch_data
2
- description: Fetch one or more records. Use to find records entities. To use this skill you first need to call get_resource tool to know resource column names. This tool returns only atomic record(s) not capable with any aggregations.
3
- ---
4
-
5
- # Involved tools
6
-
7
- You can use tool `get_resource_data` it returns one or more records and is capable of using filters
8
-
9
- When you only need specific fields, pass `columns` with the exact resource column names you need. This keeps large result sets small. For record links or user-facing record choices, include the primary key and enough display fields, or omit `columns` when you need the full row context.
10
-
11
- # Instructions
12
-
13
- To find specific data record you should use filters. ILIKE filters are preferred when we are unsure the input is clear. Pass raw search text to LIKE and ILIKE filters; never wrap filter values in SQL wildcards such as `%`. You can combine filters with OR if you want to search multiple fields. If user queries one record you should try to fetch up to 5 records and if more then one returned return output them all to user and ask to select one. When you communicate about record with user, show its several most important fields.
14
-
15
- Every record summary must be based on one exact row returned by `get_resource_data`.
16
-
17
- Never combine model/title/name, `_label`, primary key, link, or any field values from different rows.
18
-
19
- Never combine fields from different resources in one candidate.
20
-
21
- If results come from multiple resources, present them as separate groups with the resource label or resourceId.
22
-
23
- If several rows look similar, do not guess which one is "the same" record. Show them separately and ask user to choose.
24
-
25
- For long texts show only several first words and add "..." at the end (only if user did not request this field specifically).
26
-
27
- Never show information about more than 10 records in one message. If a tool returns more than 10 relevant records, summarize the total count if known, show only the 10 most relevant records, and offer to narrow filters, sort differently, or continue with the next 10.
28
-
29
- Also when you communicate with user about record, add related link to this record. Build it as `{ADMIN_BASE_PATH}resource/{resourceId}/show/{primary key}`. Use _label from `get_resource_data` as anchor text for link (use markdown link). Links should always be relative paths and must start with `ADMIN_BASE_PATH`. Do not add an extra slash after `ADMIN_BASE_PATH`.
30
-
31
- Before sending the link, verify that the `resourceId`, `{primary key}`, `_label`, and shown fields come from the same exact returned row.