AI tools
In the ecosystem, tools are the actions the AI can take — read the canvas (gh_get), place components (gh_put), generate scripts (script_generate), search forums (discourse_*), fetch files and web pages, and ~100 more. The same catalog feeds three consumers: the canvas assistant/AI Chat (function calling), the MCP server, and components that call tools directly.
See the AI Tools Library for the catalog; this page is about writing a new one.
Structure of a tool
A tool is a single class with a single-member contract — IAIToolProvider.GetTools() yields AITool instances, each binding metadata (name, description, JSON schemas, annotations) to an execute delegate:
| Piece | What it is |
|---|---|
name | Stable snake_case identifier — the LLM and tool filters address it by this (gh_get, script_review). |
description + parametersSchema + outputSchema | The tool's interface: what the LLM reads to decide when/how to call it. |
execute | Func<AIToolCall, Task<AIReturn>> — the implementation, covered below. |
mutatesCanvas, enabled, tags, annotations, surfaces | Flags controlling who can see it and whether consent review applies. |
- Implementations:
src/SmartHopper.Core.Grasshopper/AITools/— one file per tool, class implementsIAIToolProvider(gh_*.cs,script_*.cs,web2md.cs…). - Contract + manager:
SmartHopper.Infrastructure/AITools/—AITool,AIMutatingTool,ToolManager,AIToolCall. - Discovery: the tool manager instantiates every
IAIToolProviderin the trustedSmartHopper.Core.Grasshopper.AIToolsnamespace. No registration call — adding a class in that namespace is all it takes.
The contract
IAIToolProvider yields AITool instances with metadata + an execute delegate:
public IEnumerable<AITool> GetTools()
{
yield return new AITool(
name: "my_tool",
description: "What the LLM reads when deciding to call this tool. Be specific about inputs, outputs, and when NOT to use it.",
category: "Knowledge",
parametersSchema: @"{
""type"": ""object"",
""properties"": {
""query"": { ""type"": ""string"", ""description"": ""…"" }
},
""required"": [""query""]
}",
execute: this.MyToolAsync,
requiredCapabilities: AICapability.None,
mutatesCanvas: false, // ⚠ defaults to true — set false for read-only tools
enabled: true,
tags: new[] { "search", "read-only" },
outputSchema: @"{ ""type"": ""object"", ""properties"": { … } }",
annotations: new AIToolAnnotations(
openWorldHint: true, // talks to the outside world
readOnlyHint: true,
destructiveHint: false));
}
Full constructor (SmartHopper.Infrastructure/AITools/AITool.cs):
| Parameter | Purpose |
|---|---|
name | Stable identifier — the LLM and filters address the tool by it (gh_get, script_review). |
description | The LLM's decision text. GetRichDescription() prepends mutability info and appends tags. |
category | Grouping bucket (drives default tags too). |
parametersSchema / outputSchema | JSON schemas for arguments and the result payload — consumed by both the LLM and MCP clients. |
execute | Func<AIToolCall, Task<AIReturn>> — the implementation. |
requiredCapabilities | AICapability the model needs (e.g. tools that hand work back to the LLM); None for local tools. |
buildRequest | Optional: build an AIRequestCall without executing — enables batch mode. null = sync-only. |
mutatesCanvas | Defaults to true. Set false for read-only tools — it controls annotations, MCP exposure defaults, and whether consent review applies. |
enabled | Disabled tools are hidden everywhere (assistant, MCP, components). |
tags | Extra tags; defaults are derived from category + mutability. |
annotations | MCP hints: readOnlyHint, destructiveHint, idempotentHint, openWorldHint, title. Auto-derived from mutatesCanvas if omitted. |
surfaces | AIToolSurface flags — where the tool is exposed (below). |
Surfaces
AIToolSurface (ProviderSdk.Hosting) is a flags enum:
| Flag | Exposes the tool to |
|---|---|
Chat | The in-app assistant (WebChat) |
Direct | Components and direct API callers (UsingAiTools) |
Batch | Provider batch collection |
Mcp | The MCP server (tools/list, tools/call) |
All | Every surface (the default for AITool) |
AIMutatingTool — the subclass for canvas/document changes — defaults to Chat | Direct | Mcp and strips Batch automatically: a mutating tool can never run inside a batch collection.
The execute delegate
Tools receive an AIToolCall and must return an AIReturn whose body contains an AIInteractionToolResult:
private async Task<AIReturn> MyToolAsync(AIToolCall toolCall)
{
var output = new AIReturn { Request = toolCall };
try
{
// Local tool (no provider call): provider/model metrics aren't meaningful.
toolCall.SkipMetricsValidation = true;
var call = toolCall.GetToolCall(); // AIInteractionToolCall (Id, Name, Arguments)
var args = call.GetArgumentsOrEmpty(); // JObject — defensively empty on bad input
var query = args["query"]?.ToString();
if (string.IsNullOrWhiteSpace(query))
{
output.CreateError("Parameter 'query' is required.");
return output;
}
var result = await DoSearch(query, toolCall.CancellationToken);
var body = AIBodyBuilder.Create()
.AddToolResult(result, call.Id, call.Name)
.Build();
output.CreateSuccess(body, toolCall);
return output;
}
catch (Exception ex)
{
output.CreateError($"Error executing {ToolName}: {ex.Message}");
return output;
}
}
Conventions:
- Return errors, don't throw.
CreateErrorproduces a cleanAIReturnthe session can feed back to the model or show the user; exceptions get caught by the manager anyway but lose your message. - Match results to the call via
AddToolResult(result, call.Id, call.Name)— that's howConversationSessionpairs results with pendingAIInteractionToolCalls. - Honor
toolCall.CancellationToken— users cancel mid-run. - Validate/sanitize arguments — the LLM can and will pass wrong shapes.
SkipMetricsValidation = truefor purely local tools that never hit a provider.
Mutating tools and consent
Tools that change the canvas go through AIMutatingTool and — for Grasshopper document changes — the review service, so the user sees a diff/consent step before anything is applied. The pattern (from gh_select):
yield return new AIMutatingTool(
name: "my_mutating_tool",
description: "…",
category: "Components",
parametersSchema: @"{…}",
execute: this.MutateAsync,
tags: new[] { "canvas", "mutating" },
outputSchema: @"{…}",
annotations: new AIToolAnnotations(destructiveHint: false));
private async Task<AIReturn> MutateAsync(AIToolCall toolCall)
{
// 1. Filter out protected objects — they can never be touched.
var (allowed, skipped) = CanvasProtection.FilterProtectedGuids(requestedGuids);
// 2. Propose the change set and ask for consent.
var session = CanvasChangeReviewService.CreateComponentStateSession(
ToolName, allowed, "Short review label");
var accepted = session.Items.Count > 0
&& await CanvasChangeReviewService.ReviewAsync(
session, toolCall.InvocationContext, toolCall.CancellationToken);
// 3. Apply ONLY what was accepted.
if (accepted)
{
Apply(CanvasChangeReviewService.GetAcceptedComponentGuids(session));
}
…
}
Rules for mutating tools:
- Never touch protected components — route every GUID through
CanvasProtection. - Propose, don't apply — build the review session from exactly the objects you'll change, then apply only the accepted set.
- Report skipped/missing/mismatch in the result
JObject(seegh_select'sskippedProtected,missingGuids) so the model knows the outcome wasn't total. - Undo — register undo records for changes the user might want to revert (repo rule
grasshopper-undo.md).
Using a tool from code
Never call execute directly — go through the manager / AIToolCall so validation, surfaces, and cancellation apply:
// Inside a component (AIStatefulAsyncComponentBase gives you this):
var result = await this.CallAIToolAsync("text2text", parameters, token);
// result is a JObject — the tool's result payload
Components declare the tools they need via UsingAiTools and get a managed session — see Components.
Checklist for a new tool
- Class in
SmartHopper.Core.Grasshopper/AITools/implementingIAIToolProvider(discovery is automatic). -
mutatesCanvas: falseexplicitly on read-only tools. -
AIMutatingTool+ review-service flow for canvas changes. - Real
parametersSchema/outputSchema/annotations— the LLM, MCP clients, and docs all consume them. - Errors via
CreateErrorwith actionable text; results viaAddToolResult. -
CancellationTokenhonored; Rhino/GH UI access marshalled to the UI thread. - A test in
SmartHopper.Core.Grasshopper.Tests/AITools/where feasible (many existing tool tests there don't need Rhino activation).