Core Concepts & APIs (OptimizelyOpal.OpalToolsSDK)
Outline
To access the SDK, please visit: https://www.nuget.org/packages/OptimizelyOpal.OpalToolsSDK
This module introduces you to the fundamental building blocks of the Optimizely Opal Tools SDK for C#. We'll explore how to install it and understand the key features and APIs that simplify the process of creating Opal-compatible tool services using C# and ASP.NET Core.
By the end of this module, you will be able to:
- Install and set up the C# SDK in your project.
- Build tools that integrate with existing .NET applications, databases, or enterprise systems.
- Leverage advanced C# features like dependency injection for complex scenarios.
Installation and Project Setup
Before you can use the SDK, you need to set up your .NET project and install the package.
Prerequisites:
.
NET SDK (version 6.0+ recommended) installed.
A basic understanding of C# and ASP.NET Core project structure.
An IDE like Visual Studio or VS Code with C# extensions.
Steps to Install:
- Create a new ASP.NET Core Web API project: This is a common starting point for C# Opal tools, as they are essentially web services.
dotnet new webapi -n MyOpalCSharpTools
cd MyOpalCSharpTools
- Install the Optimizely Opal Tools SDK:
dotnet add package OptimizelyOpal.OpalToolsSDK
# Or using NuGet Package Manager Console in Visual Studio:
# Install-Package OptimizelyOpal.OpalToolsSDK
This command adds the package reference to your .csproj file.
- Configure
Program.cs: You'll need to integrate the Opal Tools Service into your ASP.NET Core application's startup. InProgram.cs, typically beforeapp.Run():
using OptimizelyOpal.OpalToolsSDK;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at
https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
// Add the Opal Tools Service to the dependency injection container
builder.Services.AddOpalToolsService(); // This registers necessary services
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
// Register Opal Tools and add its middleware
app.UseOpalToolsService(); // This adds the /discovery and tool execution endpoints
app.Run();
The [Tool] Attribute
The [Tool] attribute is the primary way to define your Opal tools in C#. You apply it to a static method to tell the Opal SDK that this method should be exposed as a callable tool.
- Purpose: It simplifies the process of registering your tool with the SDK. The attribute provides metadata (name, description, parameters) that the SDK uses to generate the tool manifest and set up the necessary HTTP endpoints (discovery and execution) within your ASP.NET Core application.
- Usage: You'll typically apply
[Tool]to a static method that contains your tool's logic. The attribute takesnameanddescriptionparameters. The method's parameters will be automatically mapped to the tool's input parameters.
ASP.NET Core Integration
The C# SDK is designed to work seamlessly with ASP.NET Core, a high-performance framework for building web applications and APIs with .NET.
- Automatic Endpoint Setup: The SDK leverages ASP.NET Core's routing to automatically set up:
- The
/discoveryendpoint: This is the endpoint Opal calls to discover all the tools your service offers. The SDK generates and serves the tool manifest dynamically. - Tool execution routes: For each tool you define with
[Tool], the SDK creates a corresponding HTTP route (e.g.,/tools/your_tool_name) that Opal will call to execute your tool.
- The
- Benefits: ASP.NET Core's robust features, including dependency injection, configuration management, and middleware pipeline, greatly enhance the development experience for Opal tools.
Parameter Models
When defining your tool's parameters, you'll typically use plain old C# objects (POCOs) as parameter models. The SDK uses the properties of these models to infer the tool's schema in the manifest and perform validation.
- Importance: Using strongly-typed models ensures type safety, provides excellent IntelliSense in your IDE, and allows for clear definition of the expected input structure.
- Supported Types: Standard C# types like
string,int,double,bool,List<t>,Dictionary<tkey tvalue>, and custom classes for complex objects
The [RequiresAuth] Attribute
Security is crucial. The [RequiresAuth] attribute allows you to specify authentication requirements for your tool methods.
- Purpose: This attribute informs Opal about the expected authentication provider and scope bundle, and the SDK can enforce these requirements before executing the tool method.
- Usage: You apply
[RequiresAuth]to your tool method, specifying aprovidername and an optionalscopeBundle.
Example of a Basic C# Opal Tool Service (Program.cs and a Tools.cs file):
First, ensure your Program.cs is configured as shown in step 3 of "Installation and Project Setup" above.
Then, create a new file, e.g., Tools.cs, in your project:
using OptimizelyOpal.OpalToolsSDK.Attributes;
using OptimizelyOpal.OpalToolsSDK.Models; // For ParameterType if needed, though often inferred
namespace MyOpalCSharpTools.Tools
{
// Define a simple parameter model
public class GreetingParams
{
public string Name { get; set; }
public string Language { get; set; } = "en"; // Default value
}
// Define a class to hold your static tool methods
public static class MySimpleTools
{
[Tool(name: "hello_world", description: "A simple tool that returns a greeting.")]
public static object HelloWorldTool(GreetingParams parameters)
{
string greeting;
if (parameters.Language == "es")
{
greeting = $"¡Hola, {parameters.Name} desde la herramienta Opal!";
}
else
{
greeting = $"Hello, {parameters.Name} from Opal Tool!";
}
return new { message = greeting };
}
// Example of a tool with no parameters
[Tool(name: "get_current_time", description: "Returns the current UTC time.")]
public static object GetCurrentTimeTool()
{
return new { currentTimeUtc = DateTime.UtcNow.ToString("o") }; // ISO 8601 format
}
}
}
To run this application:
- Save your code.
- Open your terminal in the project directory (
MyOpalCSharpTools). - Run:
dotnet run - Then access:
- Discovery endpoint:
<a href="http://localhost:5000/discovery">http://localhost:5000/discovery</a>(or whatever port your app starts on, usually 5000/5001) - Try calling the tool:
POST <a href="http://localhost:5000/tools/hello_world">http://localhost:5000/tools/hello_world</a>with JSON body:{ "name": "Opal", "language": "es" }
- Discovery endpoint:
In the next module, we'll dive deeper into defining tools and their parameters with more practical examples.
