Method InvokeAsync
InvokeAsync(string, CancellationToken)
Executes the tool with the specified JSON arguments.
public Task<string> InvokeAsync(string arguments, CancellationToken cancellationToken = default)
Parameters
argumentsstringA JSON string representing an object that conforms to InputSchema. The agent runtime passes this directly from the model's tool call.
cancellationTokenCancellationTokenA token to monitor for cancellation requests. Propagate this to any async operations within the tool.
Returns
- Task<string>
A JSON string containing the tool's result. This is passed back to the model so it can incorporate the result into its response.
Examples
Example: Implementing InvokeAsync with proper error handling
public async Task<string> InvokeAsync(string arguments, CancellationToken cancellationToken = default)
{
// Parse arguments
SearchArgs args;
try
{
args = JsonSerializer.Deserialize<SearchArgs>(arguments);
}
catch (JsonException ex)
{
throw new ArgumentException($"Invalid arguments: {ex.Message}", ex);
}
// Validate
if (string.IsNullOrWhiteSpace(args.Query))
{
throw new ArgumentException("Query cannot be empty");
}
// Execute with cancellation support
cancellationToken.ThrowIfCancellationRequested();
var results = await _searchService.SearchAsync(args.Query, args.MaxResults, cancellationToken);
// Return structured JSON
return JsonSerializer.Serialize(new
{
query = args.Query,
totalResults = results.Total,
items = results.Items.Select(i => new { i.Title, i.Url, i.Snippet })
});
}
Remarks
Implementation Guidelines:
-
Parse
argumentsand validate against expected schema. - Throw ArgumentException for invalid or malformed arguments.
- Throw HttpRequestException for network failures.
-
Respect
cancellationTokenand throw OperationCanceledException when cancelled. - Return compact, structured JSON. Avoid large blobs unless necessary.
Error Handling: Exceptions thrown from this method are caught by the runtime and converted to error results that the model can see. Design your error messages to be informative but safe for model consumption.