@adminforth/agent 3.1.9 → 3.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.
Files changed (42) 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/ChatHeader.vue +1 -1
  6. package/dist/custom/{skills/charts/SKILL.md → charts.md} +2 -4
  7. package/dist/domain/systemPrompt.d.ts +3 -2
  8. package/dist/domain/systemPrompt.js +14 -53
  9. package/dist/index.d.ts +0 -3
  10. package/dist/index.js +24 -35
  11. package/dist/llm/agentRuntime.d.ts +9 -8
  12. package/dist/llm/agentRuntime.js +134 -106
  13. package/dist/llm/langGraphLlm.d.ts +3 -0
  14. package/dist/llm/langGraphLlm.js +10 -2
  15. package/dist/llm/middleware/mcpToolsMiddleware.d.ts +7 -0
  16. package/dist/llm/middleware/{apiToolsMiddleware.js → mcpToolsMiddleware.js} +16 -36
  17. package/dist/tools/agentToolProvider.d.ts +16 -5
  18. package/dist/tools/agentToolProvider.js +26 -10
  19. package/dist/tools/fetchToolSchema.d.ts +7 -3
  20. package/dist/tools/fetchToolSchema.js +29 -22
  21. package/dist/tools/mcpConnection.d.ts +38 -0
  22. package/dist/tools/mcpConnection.js +42 -0
  23. package/dist/tools/mcpTool.d.ts +3 -0
  24. package/dist/tools/{apiTool.js → mcpTool.js} +7 -23
  25. package/dist/tools/toolLabels.d.ts +5 -0
  26. package/dist/tools/toolLabels.js +49 -0
  27. package/dist/transport/http/context.d.ts +2 -2
  28. package/dist/transport/http/sessionEndpoints.js +1 -1
  29. package/package.json +6 -4
  30. package/dist/custom/skills/analyze_data/SKILL.md +0 -25
  31. package/dist/custom/skills/fetch_data/SKILL.md +0 -31
  32. package/dist/custom/skills/mutate_data/SKILL.md +0 -121
  33. package/dist/llm/middleware/apiToolsMiddleware.d.ts +0 -3
  34. package/dist/tools/apiBasedTools.d.ts +0 -30
  35. package/dist/tools/apiBasedTools.js +0 -488
  36. package/dist/tools/apiTool.d.ts +0 -6
  37. package/dist/tools/fetchSkill.d.ts +0 -8
  38. package/dist/tools/fetchSkill.js +0 -51
  39. package/dist/tools/index.d.ts +0 -4
  40. package/dist/tools/index.js +0 -32
  41. package/dist/tools/skills/registry.d.ts +0 -11
  42. package/dist/tools/skills/registry.js +0 -107
package/README.md CHANGED
@@ -5,8 +5,9 @@
5
5
  [![Ask AI](https://tluma.ai/badge)](https://tluma.ai/ask-ai/devforth/adminforth)
6
6
 
7
7
  Adds a native, tool-calling AI agent to your AdminForth application. The agent lives in a
8
- chat panel inside the admin UI, can inspect and mutate your resources through safe
9
- API-based tools, streams its answers token-by-token, and keeps persistent chat sessions.
8
+ chat panel inside the admin UI, can inspect and mutate your resources through the tools of
9
+ the [AdminForth MCP server](https://adminforth.dev/docs/tutorial/Plugins/mcp/), streams its
10
+ answers token-by-token, and keeps persistent chat sessions.
10
11
 
11
12
  > Full tutorial: [AdminForth Agent Documentation](https://adminforth.dev/docs/tutorial/Plugins/agent/)
12
13
 
@@ -14,7 +15,8 @@ API-based tools, streams its answers token-by-token, and keeps persistent chat s
14
15
 
15
16
  - **Chat agent in the admin UI** — a streaming chat surface injected into every page.
16
17
  - **Tool calling over your resources** — the agent reads and (optionally) mutates records
17
- through AdminForth's own API layer, so your access rules and validation still apply.
18
+ through the `@adminforth/mcp` plugin, which runs AdminForth's own API handlers as the user,
19
+ so your access rules, hooks and validation still apply.
18
20
  - **Progressive tool & skill disclosure** — the agent loads only the tools it needs, guided
19
21
  by Markdown *skills* you can extend.
20
22
  - **Human-in-the-loop approvals** — tools you mark as dangerous pause for explicit
@@ -35,10 +37,11 @@ Built on [LangChain / LangGraph](https://github.com/langchain-ai/langgraphjs).
35
37
 
36
38
  ## How it works
37
39
 
38
- For each user message the plugin creates a *turn*, builds the system prompt (including the
39
- list of your resources and available skills), streams the model's output back over SSE, and
40
- persists the prompt/response to your turn resource. Tools are executed through AdminForth's
41
- API endpoints; conversation memory is kept per session (`thread_id = sessionId`).
40
+ For each user message the plugin creates a *turn*, opens an in-process connection to the
41
+ `@adminforth/mcp` server as the user, builds the system prompt (the MCP server instructions
42
+ with its skills, followed by the agent's own rules), streams the model's output back over SSE,
43
+ and persists the prompt/response to your turn resource. Every tool call is an MCP `tools/call`
44
+ on that connection; conversation memory is kept per session (`thread_id = sessionId`).
42
45
 
43
46
  ## Architecture
44
47
 
@@ -50,7 +53,7 @@ completion adapter, the checkpointer) sit behind ports and never leak into the t
50
53
  | Domain — prompt building, event vocabulary, buffers | [domain/](domain/) | adminforth types only |
51
54
  | Application — the turn use case + ports | [application/](application/) | domain |
52
55
  | LLM runtime — LangChain/LangGraph behind `LlmPort` | [llm/](llm/) | application, domain, tools |
53
- | Tools & skills — API tools, progressive disclosure | [tools/](tools/) | AdminForth API layer |
56
+ | Tools — MCP connection, progressive disclosure | [tools/](tools/) | `@adminforth/mcp` |
54
57
  | Persistence — sessions, turns, checkpoints | [persistence/](persistence/) | AdminForth resources |
55
58
  | Transport — HTTP endpoints, SSE, external surfaces | [transport/](transport/) | application |
56
59
  | Frontend — Vue 3 + Pinia chat surface | [custom/](custom/) | HTTP + SSE contract |
@@ -62,9 +65,10 @@ flowchart TB
62
65
  APP["application/<br/>RunTurnUseCase + LlmPort"]
63
66
  DOM["domain/<br/>prompt building, steer buffer,<br/>events, language detection"]
64
67
  LLMS["llm/<br/>LangGraph agent, middleware chain, models"]
65
- TLS["tools/<br/>API tools + skills,<br/>progressive disclosure"]
68
+ TLS["tools/<br/>MCP connection,<br/>progressive disclosure"]
66
69
  PRS["persistence/<br/>sessions, turns, checkpoints"]
67
70
 
71
+ MCPS(["@adminforth/mcp<br/>tools, skills, 2FA confirmation"])
68
72
  AF[("AdminForth core<br/>resources, API layer, auth")]
69
73
  MODEL(["Completion adapter<br/>OpenAI / Anthropic / Gemini"])
70
74
  ADPT(["Audio and chat surface adapters<br/>STT / TTS, Telegram"])
@@ -79,12 +83,15 @@ flowchart TB
79
83
  LLMS --> MODEL
80
84
  LLMS --> TLS
81
85
  LLMS -->|"checkpointer"| PRS
82
- TLS --> AF
86
+ TLS -->|"in-process MCP"| MCPS
87
+ MCPS --> AF
83
88
  PRS --> AF
84
89
  ```
85
90
 
86
91
  Every arrow into `AdminForth core` goes through its ordinary resource/API layer, so your
87
92
  access rules, hooks and validation apply to the agent exactly as they do to a human admin.
93
+ The agent has exactly the permissions of the user it runs for: the MCP `readOnly` option
94
+ applies to MCP clients only.
88
95
 
89
96
  ### One turn, end to end
90
97
 
@@ -98,7 +105,7 @@ sequenceDiagram
98
105
  participant DB as sessions and turns
99
106
  participant LLM as LangGraphLlm + AgentRuntime
100
107
  participant M as Model (completion adapter)
101
- participant T as API tool (AdminForth API layer)
108
+ participant T as MCP tool (@adminforth/mcp)
102
109
 
103
110
  U->>UI: type a message
104
111
  UI->>EP: message, sessionId, mode, timeZone, currentPage
@@ -115,14 +122,14 @@ sequenceDiagram
115
122
  M-->>LLM: reasoning and text deltas
116
123
  LLM-->>UI: reasoning-delta and text-delta frames
117
124
  M-->>LLM: tool call
118
- alt tool has agent.requiresHumanApproval
125
+ alt tool has destructiveHint (agent.requiresHumanApproval)
119
126
  LLM-->>UI: data-interrupt, generation pauses
120
127
  U->>UI: approve or reject
121
128
  UI->>EP: POST /agent/approval
122
129
  EP->>UC: resume the interrupted graph
123
130
  else safe tool
124
- LLM->>T: execute through the API layer
125
- T-->>LLM: YAML result plus durationMs
131
+ LLM->>T: tools/call on the in-process MCP connection
132
+ T-->>LLM: YAML result
126
133
  LLM-->>UI: data-tool-call start and end
127
134
  end
128
135
  end
@@ -146,21 +153,23 @@ Two side channels run on top of that flow:
146
153
 
147
154
  ```mermaid
148
155
  flowchart LR
149
- A["Turn starts"] --> B["Exposed tools:<br/>get_resource, get_user_location,<br/>navigate_user, fetch_skill, fetch_tool_schema"]
156
+ A["Turn starts"] --> B["Exposed tools: MCP get_resources_list,<br/>get_resource, fetch_skill, wait_for_confirmation,<br/>and get_user_location, navigate_user, fetch_tool_schema"]
150
157
  B --> C{"Needs more than<br/>reading schema?"}
151
158
  C -- no --> D["Answer with the base tools"]
152
- C -- yes --> E["fetch_skill returns the SKILL.md<br/>for the matching skill"]
153
- E --> F["fetch_tool_schema loads one<br/>API tool schema by name"]
154
- F --> G["ApiBasedToolsMiddleware sees the<br/>status 200 tool message and adds that<br/>tool to the next model call"]
155
- G --> H{"agent.requiresHumanApproval?"}
159
+ C -- yes --> E["MCP fetch_skill returns<br/>the matching skill"]
160
+ E --> F["fetch_tool_schema loads one<br/>MCP tool by name"]
161
+ F --> G["McpToolsMiddleware sees the<br/>status 200 tool message and adds that<br/>tool to the next model call"]
162
+ G --> H{"destructiveHint?"}
156
163
  H -- yes --> I["humanInTheLoopMiddleware interrupt,<br/>approve or reject in the UI"]
157
- H -- no --> J["Execute through the AdminForth API layer"]
164
+ H -- no --> J["tools/call on the MCP server"]
158
165
  I -- approved --> J
159
166
  ```
160
167
 
161
168
  ## Requirements
162
169
 
163
170
  - An AdminForth app (`adminforth >= 3.8.2`, declared as a peer dependency).
171
+ - The [`@adminforth/mcp`](https://adminforth.dev/docs/tutorial/Plugins/mcp/) plugin in the same
172
+ app: the agent calls every admin panel tool through it and fails to start without it.
164
173
  - A **completion adapter** that supports agent/tool-calling. Any of these work:
165
174
  - [`@adminforth/completion-adapter-openai-responses`](https://www.npmjs.com/package/@adminforth/completion-adapter-openai-responses)
166
175
  - [`@adminforth/completion-adapter-anthropic-messages`](https://www.npmjs.com/package/@adminforth/completion-adapter-anthropic-messages)
@@ -171,13 +180,15 @@ flowchart LR
171
180
  ## Installation
172
181
 
173
182
  ```bash
174
- npm install @adminforth/agent @adminforth/completion-adapter-openai-responses
183
+ pnpm add @adminforth/agent @adminforth/mcp @adminforth/completion-adapter-openai-responses
175
184
  ```
176
185
 
177
186
  ## Setup
178
187
 
179
188
  Setup has three parts: (1) create the storage resources, (2) configure the plugin, and
180
- (3) register both in your AdminForth config.
189
+ (3) register both in your AdminForth config. Set up the
190
+ [MCP plugin](https://adminforth.dev/docs/tutorial/Plugins/mcp/) as its documentation describes
191
+ and add it to the same `globalPlugins`.
181
192
 
182
193
  ### 1. Create the storage resources
183
194
 
@@ -203,6 +214,10 @@ const sessionsResource: AdminForthResourceInput = {
203
214
  { name: 'asker_id', type: AdminForthDataTypes.STRING },
204
215
  { name: 'created_at', type: AdminForthDataTypes.DATETIME, fillOnCreate: () => new Date().toISOString() },
205
216
  ],
217
+ // Agent-internal data: closed to admin users and MCP clients, the agent works with it directly.
218
+ options: {
219
+ allowedActions: { list: false, show: false, create: false, edit: false, delete: false },
220
+ },
206
221
  };
207
222
 
208
223
  export default sessionsResource;
@@ -233,6 +248,10 @@ const turnsResource: AdminForthResourceInput = {
233
248
  // Optional: add a `debug` TEXT column and map it via turnResource.debugField
234
249
  // to store per-turn debug traces.
235
250
  ],
251
+ // Agent-internal data: closed to admin users and MCP clients, the agent works with it directly.
252
+ options: {
253
+ allowedActions: { list: false, show: false, create: false, edit: false, delete: false },
254
+ },
236
255
  };
237
256
 
238
257
  export default turnsResource;
@@ -269,6 +288,10 @@ const checkpointsResource: AdminForthResourceInput = {
269
288
  { name: 'writes_payload', type: AdminForthDataTypes.TEXT },
270
289
  { name: 'schema_version', type: AdminForthDataTypes.INTEGER },
271
290
  ],
291
+ // Agent-internal data: closed to admin users and MCP clients, the agent works with it directly.
292
+ options: {
293
+ allowedActions: { list: false, show: false, create: false, edit: false, delete: false },
294
+ },
272
295
  };
273
296
 
274
297
  export default checkpointsResource;
@@ -400,29 +423,35 @@ plus two optional ones:
400
423
 
401
424
  ## Tools & skills
402
425
 
403
- The agent works through **API-based tools** generated from your AdminForth resources
404
- (reading records, inspecting schema, and — through skills — creating/updating/deleting
405
- records and running actions). Tools run via AdminForth's own API layer, so per-resource
406
- permissions and validation are enforced.
426
+ The agent has no tools of its own for your data: it is an MCP client of the
427
+ [`@adminforth/mcp`](https://adminforth.dev/docs/tutorial/Plugins/mcp/) server, connected in
428
+ process for each turn as the user who sends the message. The MCP server runs AdminForth's API
429
+ handlers, so per-resource permissions, hooks and validation are enforced, and it shows only the
430
+ resources the user may list or show.
407
431
 
408
432
  To keep the model focused, tools are disclosed progressively:
409
433
 
410
- - Always available: `get_resource` (inspect resource structure), `get_user_location`,
411
- `navigate_user`, and the two discovery tools `fetch_skill` / `fetch_tool_schema`.
412
- - The agent reads a **skill** (a `SKILL.md` file) to learn which tools a task needs, then
413
- loads those tool schemas on demand.
434
+ - Always available: the MCP tools `get_resources_list`, `get_resource`, `fetch_skill` and, with
435
+ two-factor authentication set up, `wait_for_confirmation`; and the agent's own
436
+ `get_user_location`, `navigate_user` and `fetch_tool_schema`.
437
+ - Every other MCP tool is named, with the first sentence of its description, in the
438
+ description of `fetch_tool_schema`, the way MCP clients that load tool schemas on demand
439
+ list them. The agent loads a tool with `fetch_tool_schema` before its first call, and a
440
+ **skill** loaded with `fetch_skill` tells it which tools a task needs.
414
441
 
415
- Built-in skills cover fetching data, analytics/charts, and mutating data. You can add your
416
- own skills by placing a `SKILL.md` (with `name` and `description` frontmatter) in a
417
- `skills/<skill-name>/` directory under your custom components dir; plugin-provided skill
418
- directories are also discovered.
442
+ Skills come from the MCP server: its built-in `fetch-data`, `analyze-data` and `mutate-data`, plus
443
+ every `skills/<skill-name>/SKILL.md` in your custom components dir and in other plugins. The
444
+ agent's own system prompt adds the rules of this chat and the guide for Vega-Lite charts.
445
+
446
+ Datetimes in `get_resource_data` results come in the user's time zone, which the chat UI sends
447
+ with every message.
419
448
 
420
449
  ## Human-in-the-loop approvals
421
450
 
422
- Tools whose endpoint sets `agent.requiresHumanApproval` (or the older `agent.isDangerous`) trigger an
423
- approval interrupt: generation pauses and the UI shows an approve/reject prompt. The client
424
- resolves it via `POST /agent/approval`, and the run resumes (or, on reject, the model is
425
- told the action was declined).
451
+ Tools whose endpoint sets `agent.requiresHumanApproval`, which the MCP server marks with
452
+ `destructiveHint`, trigger an approval interrupt: generation pauses and the UI shows an
453
+ approve/reject prompt. The client resolves it via `POST /agent/approval`, and the run resumes
454
+ (or, on reject, the model is told the action was declined).
426
455
 
427
456
  The prompt names the resource and columns by their labels and lists every value the tool
428
457
  would write; for `update_record` each field shows its current value next to the new one.
@@ -432,6 +461,10 @@ Where the pending approval lives depends on your setup: with `checkpointResource
432
461
  the LangGraph checkpoint is authoritative, so a resume survives a restart and works across
433
462
  instances; with the in-memory fallback the state is held per process instance.
434
463
 
464
+ Actions that need a two-factor verification run after the user confirms them on the MCP
465
+ confirmation page of the admin panel: the agent shows the link and waits with
466
+ `wait_for_confirmation`.
467
+
435
468
  ## Voice
436
469
 
437
470
  Provide an `audioAdapter` (e.g. [`@adminforth/audio-adapter-openai`](https://www.npmjs.com/package/@adminforth/audio-adapter-openai))
@@ -1,4 +1,4 @@
1
- import type { CompletionAdapter } from "adminforth";
1
+ import type { AdminUser, CompletionAdapter } from "adminforth";
2
2
  import type { DetectedLanguage, PreviousUserMessage } from "../domain/languageDetect.js";
3
3
  import type { AgentMessage, AgentStreamChunk, AgentTurnContext, AgentTurnObservability, PendingInterrupt } from "../domain/turnTypes.js";
4
4
  export type AgentModelPurpose = "primary" | "summary";
@@ -65,6 +65,7 @@ export interface LlmPort {
65
65
  getPendingInterrupts(input: {
66
66
  completionAdapter: AgentModeCompletionAdapter;
67
67
  sessionId: string;
68
+ adminUser: AdminUser;
68
69
  }): Promise<PendingInterrupt[]>;
69
70
  /**
70
71
  * Return the session thread's latest (tip) checkpoint id, or null when the thread
@@ -74,6 +75,7 @@ export interface LlmPort {
74
75
  getLatestCheckpointId(input: {
75
76
  completionAdapter: AgentModeCompletionAdapter;
76
77
  sessionId: string;
78
+ adminUser: AdminUser;
77
79
  }): Promise<string | null>;
78
80
  /**
79
81
  * Drop the entire LangGraph checkpoint thread for a session. Used when editing the
@@ -1,4 +1,4 @@
1
- import { type IAdminForth } from "adminforth";
1
+ import { type AdminUser, type IAdminForth } from "adminforth";
2
2
  import type { AgentSessionStore } from "../persistence/sessionStore.js";
3
3
  import type { SteerBuffer } from "../domain/steerBuffer.js";
4
4
  import type { PluginOptions } from "../types.js";
@@ -39,7 +39,7 @@ export type RunTurnUseCaseDeps = {
39
39
  steerBuffer: SteerBuffer;
40
40
  modes: PluginOptions["modes"];
41
41
  getAdminforth: () => IAdminForth;
42
- getAgentSystemPrompt: () => Promise<string>;
42
+ getAgentSystemPrompt: () => string;
43
43
  /** True when a persistent checkpointer is configured (not the in-memory MemorySaver). */
44
44
  hasPersistentCheckpointer: boolean;
45
45
  /**
@@ -79,7 +79,7 @@ export declare class RunTurnUseCase {
79
79
  * page reload would otherwise leave the user with no way to answer it. Empty when
80
80
  * nothing is pending.
81
81
  */
82
- getPendingApprovals(sessionId: string, modeName?: string | null): Promise<ApprovalDescription[]>;
82
+ getPendingApprovals(sessionId: string, adminUser: AdminUser, modeName?: string | null): Promise<ApprovalDescription[]>;
83
83
  private requiresSessionOwnership;
84
84
  /** Verify the session exists and belongs to the requesting admin user. */
85
85
  assertSessionOwnership(sessionId: string, adminUser: BaseAgentTurnInput["adminUser"]): Promise<void>;
@@ -101,7 +101,7 @@ export class RunTurnUseCase {
101
101
  * checkpoint is authoritative (correct across instances and restarts); with the in-memory
102
102
  * MemorySaver the in-process cache is authoritative (single process, cannot be stale).
103
103
  */
104
- resolvePendingInterrupts(sessionId, mode) {
104
+ resolvePendingInterrupts(sessionId, mode, adminUser) {
105
105
  return __awaiter(this, void 0, void 0, function* () {
106
106
  var _a;
107
107
  if (this.deps.hasPersistentCheckpointer) {
@@ -112,6 +112,7 @@ export class RunTurnUseCase {
112
112
  return yield this.deps.llm.getPendingInterrupts({
113
113
  completionAdapter: mode.completionAdapter,
114
114
  sessionId,
115
+ adminUser,
115
116
  });
116
117
  }
117
118
  catch (error) {
@@ -135,12 +136,12 @@ export class RunTurnUseCase {
135
136
  * page reload would otherwise leave the user with no way to answer it. Empty when
136
137
  * nothing is pending.
137
138
  */
138
- getPendingApprovals(sessionId, modeName) {
139
+ getPendingApprovals(sessionId, adminUser, modeName) {
139
140
  return __awaiter(this, void 0, void 0, function* () {
140
141
  // Loading a conversation must not fail because the checkpoint store is unhappy
141
142
  // (already logged by resolvePendingInterrupts). Without the prompt the user simply
142
143
  // falls back to the implicit reject in `prepareTurn`.
143
- const interrupts = yield this.resolvePendingInterrupts(sessionId, this.resolveMode(modeName))
144
+ const interrupts = yield this.resolvePendingInterrupts(sessionId, this.resolveMode(modeName), adminUser)
144
145
  .catch(() => []);
145
146
  return this.describeApprovals(interrupts);
146
147
  });
@@ -239,7 +240,7 @@ export class RunTurnUseCase {
239
240
  let initialResponse;
240
241
  let resume;
241
242
  if (shouldResume) {
242
- const resumeInterrupts = yield this.resolvePendingInterrupts(input.sessionId, mode);
243
+ const resumeInterrupts = yield this.resolvePendingInterrupts(input.sessionId, mode, input.adminUser);
243
244
  if (resumeInterrupts.length === 0) {
244
245
  throw new Error(`No pending approval interrupt found for session "${input.sessionId}".`);
245
246
  }
@@ -255,7 +256,7 @@ export class RunTurnUseCase {
255
256
  // pending call is rejected as part of this turn and the prompt rides along in
256
257
  // the rejection. Reached whenever the approval UI is gone — after a page
257
258
  // reload, from a second tab, or from a chat surface.
258
- const pending = yield this.resolvePendingInterrupts(input.sessionId, mode);
259
+ const pending = yield this.resolvePendingInterrupts(input.sessionId, mode, input.adminUser);
259
260
  previousUserMessages = yield this.deps.sessions.getPreviousUserMessages(input.sessionId);
260
261
  turnId = yield this.deps.sessions.createNewTurn(input.sessionId, input.prompt);
261
262
  yield this.deps.sessions.touchSession(input.sessionId);
@@ -341,7 +342,7 @@ export class RunTurnUseCase {
341
342
  : { messages: this.buildMessages(prepared) };
342
343
  const stream = yield this.deps.llm.streamTurn({
343
344
  completionAdapter: prepared.mode.completionAdapter,
344
- systemPrompt: yield this.deps.getAgentSystemPrompt(),
345
+ systemPrompt: this.deps.getAgentSystemPrompt(),
345
346
  input: streamInput,
346
347
  context: Object.assign(Object.assign({}, prepared.context), { userLanguage }),
347
348
  observability: prepared.observability,
@@ -440,6 +441,7 @@ export class RunTurnUseCase {
440
441
  checkpointId = yield this.deps.llm.getLatestCheckpointId({
441
442
  completionAdapter: prepared.mode.completionAdapter,
442
443
  sessionId: prepared.sessionId,
444
+ adminUser: prepared.context.adminUser,
443
445
  });
444
446
  }
445
447
  catch (error) {
@@ -2,7 +2,7 @@
2
2
  <!-- in full screen the controls line up with the centered column of the conversation -->
3
3
  <div
4
4
  ref="headerRef"
5
- class="af-agent-header flex items-center gap-0.5 h-12 px-2 border-b border-lightNavbarBorder dark:border-darkNavbarBorder"
5
+ class="af-agent-header flex items-center gap-0.5 h-14 px-2 border-b border-lightNavbarBorder dark:border-darkNavbarBorder"
6
6
  :style="agentStore.isFullScreen ? { paddingInline: `max(0.5rem, calc((100% - ${agentStore.MAX_WIDTH}rem) / 2 + 0.5rem))` } : undefined"
7
7
  >
8
8
  <Button
@@ -1,8 +1,6 @@
1
- name: charts
2
- description: Create Vega-Lite chart specs for AdminForth analytics responses. Always use this skill when the user asks for a chart or when a chart would help illustrate the insights from an analytics query.
3
- ---
1
+ # Charts
4
2
 
5
- # Instructions
3
+ Add a chart when the user asks for one or when it helps to illustrate the insights of an analytics answer. The chat renders Vega-Lite specs.
6
4
 
7
5
  Use Vega-Lite syntax for charts.
8
6
 
@@ -1,11 +1,12 @@
1
- import type { AdminUser, IAdminForth } from "adminforth";
1
+ import type { AdminUser } from "adminforth";
2
2
  import type { DetectedLanguage } from "./languageDetect.js";
3
3
  export declare const DEFAULT_AGENT_SYSTEM_PROMPT: string;
4
4
  export declare function appendCustomSystemPrompt(systemPrompt: string, customSystemPrompt?: string): string;
5
5
  export declare function buildDynamicSystemPrompt(input: {
6
6
  adminUser: AdminUser;
7
7
  usernameField: string;
8
+ userTimeZone: string;
8
9
  userLanguage?: DetectedLanguage | null;
9
10
  chatSurface?: string;
10
11
  }): string;
11
- export declare function buildAgentSystemPrompt(adminforth: IAdminForth, hiddenResourceIds?: Iterable<string>): Promise<string>;
12
+ export declare function buildAgentSystemPrompt(adminBasePath: string, chartsGuide: string): string;
@@ -1,13 +1,3 @@
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 { listProjectSkillManifests, } from "../tools/skills/registry.js";
11
1
  export const DEFAULT_AGENT_SYSTEM_PROMPT = [
12
2
  "You are helpful AI Assistant for Admin Panel.",
13
3
  // about admin
@@ -55,53 +45,24 @@ export function buildDynamicSystemPrompt(input) {
55
45
  var _a;
56
46
  return [
57
47
  formatAdminUserPrompt(input.adminUser, input.usernameField),
48
+ `User time zone: ${input.userTimeZone}. Read the dates the user mentions in it, and pass datetimes in tool arguments in UTC, ending with Z.`,
58
49
  input.chatSurface
59
50
  ? `Current chat surface: ${input.chatSurface}. The user is not in the AdminForth web UI, so tools cannot move their browser. When navigate_user returns a link, send that link to the user.`
60
51
  : "",
61
52
  formatLanguagePrompt((_a = input.userLanguage) !== null && _a !== void 0 ? _a : null),
62
53
  ].filter(Boolean).join("\n\n");
63
54
  }
64
- function formatResources(resources) {
65
- return resources
66
- .map((resource) => `- resourceId: ${resource.resourceId}\n label: ${resource.label}`)
67
- .join("\n");
68
- }
69
- function formatSkills(skills, label) {
70
- return skills
71
- .map((skill) => `- ${label}: ${skill.name}\n description: ${skill.description}`)
72
- .join("\n");
73
- }
74
- export function buildAgentSystemPrompt(adminforth_1) {
75
- return __awaiter(this, arguments, void 0, function* (adminforth, hiddenResourceIds = []) {
76
- var _a;
77
- const customComponentsDir = (_a = adminforth.config.customization.customComponentsDir) !== null && _a !== void 0 ? _a : "custom";
78
- const pluginCustomFolderPaths = adminforth.activatedPlugins
79
- .map((plugin) => plugin.customFolderPath);
80
- const skills = yield listProjectSkillManifests(customComponentsDir, pluginCustomFolderPaths);
81
- const adminBasePath = adminforth.config.baseUrlSlashed;
82
- const hiddenResourceIdSet = new Set(hiddenResourceIds);
83
- const visibleResources = adminforth.config.resources.filter((resource) => !hiddenResourceIdSet.has(resource.resourceId));
84
- const sections = [
85
- DEFAULT_AGENT_SYSTEM_PROMPT,
86
- `ADMIN_BASE_PATH: ${adminBasePath}`,
87
- `List of resources:\n${formatResources(visibleResources)}`,
88
- skills.length > 0
89
- ? `You have skills set:\n${formatSkills(skills, "skill_name")}`
90
- : "",
91
- "Before using any skill, call fetch_skill to load its full instructions.",
92
- "The fetched skill response starts with 'Tools mentioned in this skill'. Read that list first.",
93
- "You can use get_resource immediately to inspect resource structure and column names.",
94
- "If the user wants to create, update, delete, or run actions on records, load mutate_data first.",
95
- "If the user wants to fetch records, load fetch_data first. If the user wants analytics or charts, load analyze_data first.",
96
- "Only call fetch_tool_schema for tool names that are explicitly mentioned in a fetched skill and are not already available as base tools.",
97
- "If a fetched skill lists a non-base tool you need, call fetch_tool_schema for it immediately instead of telling the user the tool is unavailable.",
98
- "For example: for record creation load mutate_data, read its tool list, call fetch_tool_schema for create_record, describe the planned record, and then use create_record.",
99
- "When fetch_tool_schema succeeds, that tool becomes available on the next step.",
100
- "All admin links must be root-relative and start with '/'.",
101
- "Build record links as '/resource/{resourceId}/show/{primary key}'. Never use bare 'resource/{resourceId}/show/{primary key}' without the leading slash.",
102
- "When the user asks to open or show a page in the AdminForth UI, call navigate_user instead of only sending a link.",
103
- "Try to call as many tools as possible in parallel in one step.",
104
- ];
105
- return sections.filter(Boolean).join("\n\n");
106
- });
55
+ export function buildAgentSystemPrompt(adminBasePath, chartsGuide) {
56
+ return [
57
+ DEFAULT_AGENT_SYSTEM_PROMPT,
58
+ `ADMIN_BASE_PATH: ${adminBasePath}`,
59
+ "The MCP server rules above are written for every client. In this chat, the runtime approval UI replaces a confirmation in chat, and there is no limit on tool calls per request.",
60
+ "The description of fetch_tool_schema lists every admin panel tool you cannot call yet. Load a tool with fetch_tool_schema before its first call, right away instead of telling the user the tool is unavailable; it becomes available on the next step. A fetched skill lists the tools it uses under '# Tools'.",
61
+ "For example: for record creation load mutate-data, call fetch_tool_schema for create_record, describe the planned record, and then use create_record.",
62
+ "All admin links must be root-relative and start with '/'.",
63
+ "Build record links as '/resource/{resourceId}/show/{primary key}'. Never use bare 'resource/{resourceId}/show/{primary key}' without the leading slash.",
64
+ "When the user asks to open or show a page in the AdminForth UI, call navigate_user instead of only sending a link.",
65
+ "Try to call as many tools as possible in parallel in one step.",
66
+ chartsGuide,
67
+ ].join("\n\n");
107
68
  }
package/dist/index.d.ts CHANGED
@@ -4,7 +4,6 @@ import type { PluginOptions } from './types.js';
4
4
  export type { AgentEvent, AgentEventEmitter } from "./domain/agentEvents.js";
5
5
  export default class AdminForthAgentPlugin extends AdminForthPlugin {
6
6
  options: PluginOptions;
7
- agentSystemPromptPromise: Promise<string>;
8
7
  pluginsScope: "resource" | "global";
9
8
  private agentSystemPrompt;
10
9
  private checkpointer;
@@ -14,8 +13,6 @@ export default class AdminForthAgentPlugin extends AdminForthPlugin {
14
13
  private speechTurnService;
15
14
  private chatSurfaceService;
16
15
  private getCheckpointer;
17
- private getInternalAgentResourceIds;
18
- private getAgentSystemPrompt;
19
16
  constructor(options: PluginOptions);
20
17
  modifyGlobalConfig(adminforth: IAdminForth): Promise<void>;
21
18
  validateConfigAfterDiscover(adminforth: IAdminForth, resourceConfig: AdminForthResource): void;
package/dist/index.js CHANGED
@@ -7,10 +7,12 @@ 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 { AdminForthPlugin, logger } from "adminforth";
10
+ import { AdminForthPlugin } from "adminforth";
11
+ import { readFileSync } from "fs";
12
+ import path from "path";
11
13
  import { MemorySaver } from "@langchain/langgraph";
12
14
  import { AdminForthCheckpointSaver } from "./persistence/checkpointStore.js";
13
- import { appendCustomSystemPrompt, buildAgentSystemPrompt, DEFAULT_AGENT_SYSTEM_PROMPT } from "./domain/systemPrompt.js";
15
+ import { appendCustomSystemPrompt, buildAgentSystemPrompt } from "./domain/systemPrompt.js";
14
16
  import { setupCoreEndpoints } from "./transport/http/coreEndpoints.js";
15
17
  import { setupSessionEndpoints } from "./transport/http/sessionEndpoints.js";
16
18
  import { setupChatSurfaceEndpoints } from "./transport/http/chatSurfaceEndpoints.js";
@@ -23,7 +25,10 @@ import { AgentModelFactory } from "./llm/modelFactory.js";
23
25
  import { AgentRuntime } from "./llm/agentRuntime.js";
24
26
  import { SpeechTurnService } from "./transport/surfaces/speechTurnService.js";
25
27
  import { AgentToolProvider } from "./tools/agentToolProvider.js";
28
+ import { MCP_PLUGIN_CLASS_NAME } from "./tools/mcpConnection.js";
26
29
  import { SteerBuffer } from "./domain/steerBuffer.js";
30
+ // Vega-Lite guidance for the chat's chart renderer, appended to the system prompt.
31
+ const CHARTS_GUIDE_FILE = "charts.md";
27
32
  export default class AdminForthAgentPlugin extends AdminForthPlugin {
28
33
  getCheckpointer() {
29
34
  if (this.checkpointer)
@@ -33,41 +38,19 @@ export default class AdminForthAgentPlugin extends AdminForthPlugin {
33
38
  : new MemorySaver();
34
39
  return this.checkpointer;
35
40
  }
36
- getInternalAgentResourceIds() {
37
- var _a;
38
- return [
39
- this.options.sessionResource.resourceId,
40
- this.options.turnResource.resourceId,
41
- (_a = this.options.checkpointResource) === null || _a === void 0 ? void 0 : _a.resourceId,
42
- ].filter((resourceId) => Boolean(resourceId));
43
- }
44
- getAgentSystemPrompt() {
45
- return __awaiter(this, void 0, void 0, function* () {
46
- if (!this.agentSystemPrompt) {
47
- const systemPrompt = yield buildAgentSystemPrompt(this.adminforth, this.getInternalAgentResourceIds()).catch((err) => {
48
- logger.error(`Failed to build agent system prompt, falling back to default: ${err instanceof Error ? err.message : String(err)}`);
49
- return DEFAULT_AGENT_SYSTEM_PROMPT;
50
- });
51
- this.agentSystemPrompt = appendCustomSystemPrompt(systemPrompt, this.options.systemPrompt);
52
- }
53
- return this.agentSystemPrompt;
54
- });
55
- }
56
41
  constructor(options) {
57
42
  var _a;
58
43
  super(options, import.meta.url);
59
44
  this.pluginsScope = "global";
60
- this.agentSystemPrompt = null;
61
45
  this.checkpointer = null;
62
46
  this.options = options;
63
47
  this.sessionStore = new AgentSessionStore(() => this.adminforth, this.options);
64
48
  this.steerBuffer = new SteerBuffer();
65
- const toolProvider = new AgentToolProvider(() => this.adminforth, this.getInternalAgentResourceIds.bind(this));
66
49
  const runtime = new AgentRuntime({
67
50
  name: `adminforth-agent-${this.pluginInstanceId}`,
68
51
  getAdminforth: () => this.adminforth,
69
52
  getCheckpointer: this.getCheckpointer.bind(this),
70
- toolProvider,
53
+ toolProvider: new AgentToolProvider(() => this.adminforth),
71
54
  steerBuffer: this.steerBuffer,
72
55
  });
73
56
  const llm = new LangGraphLlm(runtime, new AgentModelFactory((_a = this.options.maxTokens) !== null && _a !== void 0 ? _a : 1000));
@@ -77,7 +60,7 @@ export default class AdminForthAgentPlugin extends AdminForthPlugin {
77
60
  steerBuffer: this.steerBuffer,
78
61
  modes: this.options.modes,
79
62
  getAdminforth: () => this.adminforth,
80
- getAgentSystemPrompt: this.getAgentSystemPrompt.bind(this),
63
+ getAgentSystemPrompt: () => this.agentSystemPrompt,
81
64
  hasPersistentCheckpointer: Boolean(this.options.checkpointResource),
82
65
  turnCheckpointsEnabled: Boolean(this.options.turnResource.checkpointIdField),
83
66
  sessionResource: this.options.sessionResource,
@@ -85,7 +68,6 @@ export default class AdminForthAgentPlugin extends AdminForthPlugin {
85
68
  });
86
69
  this.speechTurnService = new SpeechTurnService(this.runTurnUseCase.runAndPersistAgentResponse.bind(this.runTurnUseCase));
87
70
  this.chatSurfaceService = new ChatSurfaceService(() => this.adminforth, this.options, this.sessionStore, this.runTurnUseCase.handleTurn.bind(this.runTurnUseCase), this.runTurnUseCase.runAndPersistAgentResponse.bind(this.runTurnUseCase));
88
- this.agentSystemPromptPromise = Promise.resolve(appendCustomSystemPrompt(DEFAULT_AGENT_SYSTEM_PROMPT, this.options.systemPrompt));
89
71
  this.shouldHaveSingleInstancePerWholeApp = () => false;
90
72
  }
91
73
  modifyGlobalConfig(adminforth) {
@@ -93,7 +75,7 @@ export default class AdminForthAgentPlugin extends AdminForthPlugin {
93
75
  modifyGlobalConfig: { get: () => super.modifyGlobalConfig }
94
76
  });
95
77
  return __awaiter(this, void 0, void 0, function* () {
96
- var _a, _b;
78
+ var _a, _b, _c;
97
79
  _super.modifyGlobalConfig.call(this, adminforth);
98
80
  if (!((_a = this.options.modes) === null || _a === void 0 ? void 0 : _a.length)) {
99
81
  throw new Error("modes is required for AdminForthAgentPlugin");
@@ -115,6 +97,17 @@ export default class AdminForthAgentPlugin extends AdminForthPlugin {
115
97
  if (!this.options.sessionResource) {
116
98
  throw new Error("sessionResource is required for AdminForthAgentPlugin");
117
99
  }
100
+ // Chat history and checkpoints of the agent are not data for agents to work with.
101
+ const internalResourceIds = [
102
+ this.options.sessionResource.resourceId,
103
+ this.options.turnResource.resourceId,
104
+ (_c = this.options.checkpointResource) === null || _c === void 0 ? void 0 : _c.resourceId,
105
+ ];
106
+ for (const resource of adminforth.config.resources) {
107
+ if (internalResourceIds.includes(resource.resourceId)) {
108
+ resource.options.agent = Object.assign(Object.assign({}, resource.options.agent), { hiddenFromAgents: true });
109
+ }
110
+ }
118
111
  });
119
112
  }
120
113
  validateConfigAfterDiscover(adminforth, resourceConfig) {
@@ -123,12 +116,8 @@ export default class AdminForthAgentPlugin extends AdminForthPlugin {
123
116
  for (const chatSurfaceAdapter of (_b = this.options.chatSurfaceAdapters) !== null && _b !== void 0 ? _b : []) {
124
117
  chatSurfaceAdapter.validate();
125
118
  }
126
- this.agentSystemPromptPromise = buildAgentSystemPrompt(adminforth, this.getInternalAgentResourceIds())
127
- .then((systemPrompt) => {
128
- const finalPrompt = appendCustomSystemPrompt(systemPrompt, this.options.systemPrompt);
129
- this.agentSystemPrompt = finalPrompt;
130
- return finalPrompt;
131
- });
119
+ adminforth.getPluginByClassName(MCP_PLUGIN_CLASS_NAME);
120
+ this.agentSystemPrompt = appendCustomSystemPrompt(buildAgentSystemPrompt(adminforth.config.baseUrlSlashed, readFileSync(path.join(this.customFolderPath, CHARTS_GUIDE_FILE), "utf8")), this.options.systemPrompt);
132
121
  }
133
122
  instanceUniqueRepresentation(pluginOptions) {
134
123
  return `single`;
@@ -147,7 +136,7 @@ export default class AdminForthAgentPlugin extends AdminForthPlugin {
147
136
  }),
148
137
  runAndPersistAgentResponse: this.runTurnUseCase.runAndPersistAgentResponse.bind(this.runTurnUseCase),
149
138
  getSessionTurns: this.sessionStore.getSessionTurns.bind(this.sessionStore),
150
- getPendingApprovals: (sessionId) => this.runTurnUseCase.getPendingApprovals(sessionId),
139
+ getPendingApprovals: (sessionId, adminUser) => this.runTurnUseCase.getPendingApprovals(sessionId, adminUser),
151
140
  createNewTurn: this.sessionStore.createNewTurn.bind(this.sessionStore),
152
141
  createSystemTurn: this.sessionStore.createSystemTurn.bind(this.sessionStore),
153
142
  appendSteerToCurrentTurn: this.sessionStore.appendSteerToCurrentTurn.bind(this.sessionStore),