Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 42 additions & 0 deletions docs/en/docs-nav.json
Original file line number Diff line number Diff line change
Expand Up @@ -2671,6 +2671,48 @@
}
]
},
{
"text": "Agent Tools (Pro)",
"items": [
{
"text": "Overview",
"path": "modules/agent-tools/index.md",
"isIndex": true
},
{
"text": "Installation",
"path": "modules/agent-tools/installation.md"
},
{
"text": "Exposing Tools",
"path": "modules/agent-tools/exposing-tools.md"
},
{
"text": "Tool Policy and Management Page",
"path": "modules/agent-tools/policy.md"
},
{
"text": "Using Tools from Your Own Chat Client",
"path": "modules/agent-tools/chat-clients.md"
},
{
"text": "MCP Endpoint",
"path": "modules/agent-tools/mcp.md"
},
{
"text": "OpenIddict Setup",
"path": "modules/agent-tools/openiddict.md"
},
{
"text": "AI Management Integration",
"path": "modules/agent-tools/ai-management.md"
},
{
"text": "Security Notes and Known Limits",
"path": "modules/agent-tools/security.md"
}
]
},
{
"text": "AI Management (Pro)",
"path": "modules/ai-management/index.md"
Expand Down
137 changes: 137 additions & 0 deletions docs/en/modules/agent-tools/ai-management.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
```json
//[doc-seo]
{
"Description": "Add the signed-in user's governed agent tools to AI Management chat and govern the MCP tools of AI Management workspaces with the Volo.AIManagement.AgentTools package."
}
```

# Agent Tools: AI Management Integration

> You must have an [ABP Team or a higher license](https://abp.io/pricing) to use this module.

The `Volo.AIManagement.AgentTools` package connects Agent Tools with the [AI Management module](../ai-management/index.md). It does two things:

- It adds the signed-in user's Agent Tools tools to AI Management chat, for the workspaces you opt in. Each call is permission-checked, tenant-scoped, audited and subject to the [tool policy](./policy.md), as everywhere else.
- It governs the MCP tools attached to AI Management workspaces: an optional permission per MCP server, and a [call record](./chat-clients.md#observing-calls) for every call.

Without the package, AI Management behaves as before.

## Installation

Add the `Volo.AIManagement.AgentTools` package to the host that runs AI Management's chat, and depend on its module. The Agent Tools runtime must be in the same process, because the tools are called in-process as the current user in the current tenant:

```csharp
[DependsOn(
typeof(AIManagementAgentToolsModule),
typeof(AgentToolsAspNetCoreModule) // the Agent Tools runtime
)]
public class MyProjectNameHttpApiHostModule : AbpModule
{
public override void ConfigureServices(ServiceConfigurationContext context)
{
Configure<AbpAgentToolOptions>(options =>
{
options.IncludedRemoteServiceNames.Add("Default"); // which services are tools
});

Configure<AIManagementAgentToolsOptions>(options =>
{
options.EnabledWorkspaces.Add("Support");
});
}
}
```

When a chat turn needs Agent Tools tools and the runtime is not loaded, the turn fails with an exception that names the missing module.

## Options

```csharp
Configure<AIManagementAgentToolsOptions>(options =>
{
options.EnabledWorkspaces.Add("Support"); // by name (case-insensitive)
options.WorkspaceSelector = name => name.StartsWith("Agent-"); // or by predicate
options.MaxToolsPerTurn = 32;
options.McpServerPermissions[new Guid("0b1f6c0e-3c1a-4f55-9a52-2d1d8f6a7c11")] = "MyProjectName.UseBillingMcp"; // the MCP server's id
});
```

| Property | Default | Meaning |
| --- | --- | --- |
| `EnabledWorkspaces`, `WorkspaceSelector` | none | A workspace gets Agent Tools tools when it is listed or the predicate returns `true`. No workspace gets them by default. |
| `MaxToolsPerTurn` | `64` | At most this many Agent Tools tools per turn; the smaller of this and `AbpAgentToolOptions.MaxTools` applies. When more are available, a warning is logged once per workspace. `0` or less adds none. |
| `McpServerPermissions` | empty | MCP server id to permission name. A user without the permission does not get that server's tools. |

## Read-Only in Chat

AI Management's chat UIs have no approval step for these tools yet. So the bridge never offers a tool that is disabled or requires approval: by default the chat gets the read tools only. To offer a write tool in chat, turn its **Requires approval** switch off on the [management page](./policy.md#management-page), or use `[AgentTool(RequiresApproval = false)]`. The same tools then become available over [MCP](./mcp.md) too.

Other rules:

- A turn without an authenticated user gets no Agent Tools tools, and continues. This applies to turns that run anonymously and to turns authenticated with a client credentials token.
- A tool that is already in the turn (`search_documents`, an MCP tool or a tool the caller added) wins over an Agent Tools tool of the same name. The Agent Tools tool is skipped and a warning is logged. Rename it with `[AgentTool(Name = ...)]` to offer both.
- `search_documents` is reserved: an Agent Tools tool of that name is never added.

## MCP Server Permissions

Once the package is installed, it governs the MCP tools of every workspace, whether the workspace is opted in or not. Each MCP tool call produces one call record (tool, workspace, MCP server, user, tenant, outcome, duration; arguments redacted like Agent Tools does). There is no approval step for MCP tools.

`McpServerPermissions` restricts an MCP server to users that have a permission. It is keyed by the MCP server's id (a `Guid`), not by its name, so renaming the server keeps the restriction. A permission name that is not defined is granted to no one, so that server's tools disappear for everyone; a warning is logged.

Server ids are generated per database, so the same server has a different id in each environment. Keep the map in configuration per environment. Do not bind the configuration directly into the `Guid`-keyed dictionary: the configuration binder skips `Guid` keys without an error, and the restriction would silently not apply. Bind string keys and parse them instead:

```json
{
"AIManagementAgentTools": {
"McpServerPermissions": {
"0b1f6c0e-3c1a-4f55-9a52-2d1d8f6a7c11": "MyProjectName.UseBillingMcp"
}
}
}
```

```csharp
var configuration = context.Services.GetConfiguration();

Configure<AIManagementAgentToolsOptions>(options =>
{
var permissions = configuration
.GetSection("AIManagementAgentTools:McpServerPermissions")
.Get<Dictionary<string, string>>() ?? new();

foreach (var (id, permission) in permissions)
{
options.McpServerPermissions[Guid.Parse(id)] = permission;
}
});
```

A mistyped id then throws a `FormatException` on the first chat turn, instead of silently not applying. Find a server's id in the AI Management MCP server list or its API.

A turn without a user is not granted any permission, so a permission on every MCP server also keeps anonymous turns away from MCP tools.

## Not Covered

The bridge works through a hook of AI Management's chat client, which runs in every chat turn (normal and streaming). It does not cover:

- A workspace without an active configuration that falls back to the plain `IChatClient` registered in dependency injection.
- Custom workspace executors that do not use AI Management's chat client.
- MCP tools added to the turn by code that runs after the bridge.
- A replaced chat client resolver that does not pass the registered tool contributors to AI Management's chat client: then no Agent Tools tools are added and `McpServerPermissions` is not enforced.

The host must run the AI Management chat and the application services in the same process. A chat host that calls the application services of another host remotely cannot use the bridge for them.

## Extending the Chat Tools

The bridge is an implementation of AI Management's `IChatToolContributor` interface (namespace `Volo.AIManagement.Workspaces`, package `Volo.AIManagement.Abstractions`), which any module can implement to add, remove or wrap the tools of a chat turn:

```csharp
public interface IChatToolContributor
{
Task ContributeAsync(ChatToolContributionContext context);
}
```

All registered contributors run in registration order, once per turn, after AI Management added its RAG and MCP tools. The context carries `WorkspaceName`, `WorkspaceId`, the mutable `Options` (with `Options.Tools`), `SupportsApproval` (always `false` for now: do not add tools that require approval) and the `CancellationToken`. The user and tenant are the ambient `ICurrentUser` and `ICurrentTenant`, and can be empty.

An exception from a contributor fails the turn, because skipping a contributor that governs tools would hand ungoverned tools to the model.
199 changes: 199 additions & 0 deletions docs/en/modules/agent-tools/chat-clients.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,199 @@
```json
//[doc-seo]
{
"Description": "Give an IChatClient the current user's governed agent tools with IAgentToolProvider, handle approvals, call tools by name with IAgentToolInvoker and observe every call."
}
```

# Agent Tools: Using Tools from Your Own Chat Client

> You must have an [ABP Team or a higher license](https://abp.io/pricing) to use this module.

The tools are [Microsoft.Extensions.AI](../../framework/infrastructure/artificial-intelligence/microsoft-extensions-ai.md) `AIFunction`s, so any `IChatClient` can use them. Your code runs in the host that runs the application services (it needs `AgentToolsAspNetCoreModule`, see [Installation](./installation.md)).

## Getting the Current User's Tools

`IAgentToolProvider.GetToolsAsync(context)` returns the tools the current user may use, in the current tenant. A tool is left out when:

- the [policy](./policy.md) disables it;
- it requires approval and `context.SupportsApproval` is `false`;
- the user lacks its permissions or its required features, as far as ABP's attributes (`[Authorize]`, `[RequiresFeature]`) and the policy names of ABP's CRUD application services (`GetPolicyName`, `GetListPolicyName`, `CreatePolicyName`, `UpdatePolicyName`, `DeletePolicyName`) tell;
- the `AgentTools.Enable` feature is off.

The list keeps the model from trying tools it cannot use. It is not the security boundary: every call is checked again by ABP when it runs.

`AgentToolContext`:

| Property | Meaning |
| --- | --- |
| `SupportsApproval` | `true` when your client asks a human before running a tool that requires approval. `false` hides and refuses those tools. |
| `ClientId`, `ClientName` | Written to the audit log comment and the call record. |

Each `AgentTool` has:

| Property | Meaning |
| --- | --- |
| `Definition` | The `AgentToolDefinition`: name, description, kind, annotations, HTTP method and URL, remote service, service interface and parameters. |
| `RequiresApproval` | The effective policy value. |
| `Function` | The `AIFunction` to give to an `IChatClient`. When the tool requires approval, it is wrapped in Microsoft.Extensions.AI's `ApprovalRequiredAIFunction`. |
| `UnwrappedFunction` | The plain function, never wrapped, for hosts with their own approval flow. |

## A Minimal Chat

This service answers a question with the current user's read tools. The `IChatClient` must invoke functions, so the sample adds `UseFunctionInvocation()` (package `Microsoft.Extensions.AI`); skip it if your configured chat client already has it.

```csharp
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.AI;
using Volo.Abp.DependencyInjection;
using Volo.AgentTools;

namespace MyProjectName.Chat;

public class BookAssistant : ITransientDependency
{
private readonly IAgentToolProvider _toolProvider;
private readonly IChatClient _chatClient;

public BookAssistant(IAgentToolProvider toolProvider, IChatClient chatClient)
{
_toolProvider = toolProvider;
_chatClient = chatClient.AsBuilder().UseFunctionInvocation().Build();
}

public async Task<string> AskAsync(string question)
{
var tools = await _toolProvider.GetToolsAsync(new AgentToolContext
{
SupportsApproval = false, // no approval UI: tools that require approval are left out
ClientId = "book-assistant",
ClientName = "Book assistant"
});

var options = new ChatOptions
{
Tools = tools.Select(tool => (AITool)tool.Function).ToList()
};

var response = await _chatClient.GetResponseAsync(question, options);
return response.Text;
}
}
```

The tools run as the user and tenant that are current when the model calls them, so call `AskAsync` in the request of the signed-in user. See [Microsoft.Extensions.AI](../../framework/infrastructure/artificial-intelligence/microsoft-extensions-ai.md) for configuring the `IChatClient`.

> Do not expose a class like this as an application service that the catalogue includes: it would become a tool itself. Keep it out of the included remote services, or mark it with `[DisableAgentTool]`.

## Approvals

With `SupportsApproval = true` the provider also returns the tools that require approval, wrapped in `ApprovalRequiredAIFunction`. Microsoft.Extensions.AI's `FunctionInvokingChatClient` then does not call such a tool; it ends the turn with a `FunctionApprovalRequestContent`. Show the request to the user, and send the decision back with the conversation:

```csharp
#pragma warning disable MEAI001 // The approval types of Microsoft.Extensions.AI are experimental
var messages = new List<ChatMessage> { new(ChatRole.User, question) };
var response = await _chatClient.GetResponseAsync(messages, options);

var requests = response.Messages
.SelectMany(message => message.Contents)
.OfType<FunctionApprovalRequestContent>()
.ToList();

if (requests.Count > 0)
{
messages.AddRange(response.Messages);

var decisions = new List<AIContent>();
foreach (var request in requests)
{
// Show request.FunctionCall.Name and request.FunctionCall.Arguments to the user.
var approved = await AskTheUserAsync(request.FunctionCall);
decisions.Add(request.CreateResponse(approved));
}

messages.Add(new ChatMessage(ChatRole.User, decisions));
response = await _chatClient.GetResponseAsync(messages, options);
}
#pragma warning restore MEAI001
```

`AskTheUserAsync` stands for your own UI. Setting `SupportsApproval = true` is a promise that your client asks a human for these tools; the module cannot verify it.

A tool's function remembers whether it was listed as requiring approval. When the policy starts requiring approval after the list was built, a call through that function is refused (`AgentTools:ApprovalPolicyChanged`), even with `SupportsApproval = true`: get the tool list again.

## Calling a Tool by Name

`IAgentToolInvoker.InvokeAsync(toolName, arguments, context)` calls a tool directly. It is what the tool functions call.

```csharp
var result = await _toolInvoker.InvokeAsync(
"Book_Get",
new Dictionary<string, object?> { ["id"] = bookId },
new AgentToolContext { ClientId = "book-assistant" });
```

The invoker:

- resolves the application service interface in a new scope and calls the interface method, never the implementation or the controller directly;
- runs the call in its own transactional unit of work, so a failure rolls it back;
- binds arguments by parameter name, and fails with one validation error that names every missing or invalid argument;
- does not throw for tool failures: the result is the JSON of the return value (`{"success":true}` for a method without one), or an error line.

Error lines have the form `ERROR <ExceptionType>: <message>`. The message is what ABP would send an HTTP client (localized, without internal details or stack traces), with validation messages and the error code when there is one, for example:

```text
ERROR AbpAuthorizationException: Authorization failed! Given policy has not granted. (code: Volo.Authorization:010001)
ERROR AbpValidationException: Your request is not valid! Validation errors: [Name] The field Name must be a string with a maximum length of 128.
```

The invoker refuses before it calls the service with these error codes:

| Code | Reason |
| --- | --- |
| `AgentTools:ToolNotFound` | There is no tool with this name. |
| `AgentTools:ToolDisabled` | The policy disables the tool. |
| `AgentTools:ApprovalNotSupported` | The tool requires approval and `SupportsApproval` is `false`. |
| `AgentTools:ApprovalPolicyChanged` | The tool was listed without approval, and the policy requires it now. |
| `AgentTools:FeatureDisabled` | The `AgentTools.Enable` feature is off. |

A missing permission is not refused by the invoker itself: the call goes on, and ABP's authorization refuses and audits it. Cancelling the caller's `CancellationToken` throws `OperationCanceledException`.

## Observing Calls

Every registered `IAgentToolCallObserver` receives one `AgentToolCallRecord` per call, from chat clients and from the MCP endpoint:

```csharp
public class LoggingAgentToolCallObserver : IAgentToolCallObserver
{
private readonly ILogger<LoggingAgentToolCallObserver> _logger;

public LoggingAgentToolCallObserver(ILogger<LoggingAgentToolCallObserver> logger)
{
_logger = logger;
}

public Task OnCallAsync(AgentToolCallRecord record)
{
_logger.LogInformation(
"Agent tool {Tool} called by {User} through {Client}: {Outcome} in {Duration} ms",
record.ToolName,
record.UserName,
record.ClientId,
record.Succeeded ? "succeeded" : record.ErrorCode ?? record.ErrorType,
record.Duration.TotalMilliseconds);

return Task.CompletedTask;
}
}
```

Register it in `ConfigureServices`:

```csharp
context.Services.AddTransient<IAgentToolCallObserver, LoggingAgentToolCallObserver>();
```

The record has `ToolName`, `Arguments` (JSON, with sensitive values redacted), `Succeeded`, `ErrorType`, `ErrorCode`, `ErrorMessage`, `StartTime`, `Duration`, `UserId`, `UserName`, `TenantId`, `ClientId` and `ClientName`. An observer that throws is logged and never breaks the call.

When an audit log scope is active (it is in HTTP requests), the invoker also adds the comment `Agent tool <name> (client: <client id>; <client name>)` to the [audit log](../../framework/infrastructure/audit-logging.md).
Loading
Loading