Skip to main content

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:

PieceWhat it is
nameStable snake_case identifier — the LLM and tool filters address it by this (gh_get, script_review).
description + parametersSchema + outputSchemaThe tool's interface: what the LLM reads to decide when/how to call it.
executeFunc<AIToolCall, Task<AIReturn>> — the implementation, covered below.
mutatesCanvas, enabled, tags, annotations, surfacesFlags controlling who can see it and whether consent review applies.
  • Implementations: src/SmartHopper.Core.Grasshopper/AITools/ — one file per tool, class implements IAIToolProvider (gh_*.cs, script_*.cs, web2md.cs…).
  • Contract + manager: SmartHopper.Infrastructure/AITools/ — AITool, AIMutatingTool, ToolManager, AIToolCall.
  • Discovery: the tool manager instantiates every IAIToolProvider in the trusted SmartHopper.Core.Grasshopper.AITools namespace. 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):

ParameterPurpose
nameStable identifier — the LLM and filters address the tool by it (gh_get, script_review).
descriptionThe LLM's decision text. GetRichDescription() prepends mutability info and appends tags.
categoryGrouping bucket (drives default tags too).
parametersSchema / outputSchemaJSON schemas for arguments and the result payload — consumed by both the LLM and MCP clients.
executeFunc<AIToolCall, Task<AIReturn>> — the implementation.
requiredCapabilitiesAICapability the model needs (e.g. tools that hand work back to the LLM); None for local tools.
buildRequestOptional: build an AIRequestCall without executing — enables batch mode. null = sync-only.
mutatesCanvasDefaults to true. Set false for read-only tools — it controls annotations, MCP exposure defaults, and whether consent review applies.
enabledDisabled tools are hidden everywhere (assistant, MCP, components).
tagsExtra tags; defaults are derived from category + mutability.
annotationsMCP hints: readOnlyHint, destructiveHint, idempotentHint, openWorldHint, title. Auto-derived from mutatesCanvas if omitted.
surfacesAIToolSurface flags — where the tool is exposed (below).

Surfaces​

AIToolSurface (ProviderSdk.Hosting) is a flags enum:

FlagExposes the tool to
ChatThe in-app assistant (WebChat)
DirectComponents and direct API callers (UsingAiTools)
BatchProvider batch collection
McpThe MCP server (tools/list, tools/call)
AllEvery 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. CreateError produces a clean AIReturn the 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 how ConversationSession pairs results with pending AIInteractionToolCalls.
  • Honor toolCall.CancellationToken — users cancel mid-run.
  • Validate/sanitize arguments — the LLM can and will pass wrong shapes.
  • SkipMetricsValidation = true for purely local tools that never hit a provider.

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 (see gh_select's skippedProtected, 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/ implementing IAIToolProvider (discovery is automatic).
  • mutatesCanvas: false explicitly 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 CreateError with actionable text; results via AddToolResult.
  • CancellationToken honored; 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).