Skip to main content
Version: 0.13

.NET API

Looking for the cross-language FFI contract? See ./ffi-abi.md for call_native, call_native_with_plugin_agent, the "ERROR:" prefix, the 4 MiB BUFFER_SIZE, and the kcl_lib_dotnet cdylib. The KclLib.API.API class below is a thin C# wrapper over that single dispatcher; every typed method funnels through Call(name, args).

The .NET binding ships as the NuGet package KclLib. It bundles the prebuilt kcl_lib_dotnet native shared library plus the generated C# protobuf classes (KclLib.API.Spec). Two layers:

  • KclLib.API.API — class implementing IService, exposes all 21 typed RPC methods as instance methods on a plain C# class. Every method serialises its *Args proto, calls Call(name, bytes), parses the result proto, and surfaces the dispatcher "ERROR:..." reply as a thrown Exception.
  • Native cdylib — libkcl_lib_dotnet.so / .dylib / .dll, generated by csbindgen from the same kcl_api Rust crate that powers every other binding.

Installation​

dotnet add package KclLib

The package bundles the native runtime for linux-x64, linux-arm64, osx-x64, osx-arm64, and win-x64. No protoc or Rust toolchain required at build time.

Quick Start​

using KclLib.API;

var api = new API();
var execArgs = new ExecProgramArgs();
var path = Path.Combine("test_data", "schema.k");
execArgs.KFilenameList.Add(path);
var result = api.ExecProgram(execArgs);
Console.WriteLine(result.YamlResult);

API Reference​

ExecProgram​

Execute KCL file with arguments and return the JSON/YAML result.

Example

The content of schema.k is

schema AppConfig:
replicas: int

app: AppConfig {
replicas: 2
}

C# Code

using KclLib.API;

var execArgs = new ExecProgramArgs();
var path = "schema.k"
execArgs.KFilenameList.Add(path);
var result = new API().ExecProgram(execArgs);

ParseFile​

Parse KCL single file to Module AST JSON string with import dependencies and parse errors.

Example

The content of schema.k is

schema AppConfig:
replicas: int

app: AppConfig {
replicas: 2
}

C# Code

using KclLib.API;

var path = "schema.k"
var args = new ParseFileArgs { Path = path };
var result = new API().ParseFile(args);

ParseProgram​

Parse KCL program with entry files and return the AST JSON string.

Example

The content of schema.k is

schema AppConfig:
replicas: int

app: AppConfig {
replicas: 2
}

C# Code

using KclLib.API;

var path = "schema.k";
var args = new ParseProgramArgs();
args.Paths.Add(path);
var result = new API().ListOptions(args);

LoadPackage​

LoadPackage provides users with the ability to parse KCL program and semantic model information including symbols, types, definitions, etc.

Example

The content of schema.k is

schema AppConfig:
replicas: int

app: AppConfig {
replicas: 2
}

C# Code

using KclLib.API;

var path = "schema.k";
var args = new LoadPackageArgs();
args.ResolveAst = true;
args.ParseArgs = new ParseProgramArgs();
args.ParseArgs.Paths.Add(path);
var result = new API().LoadPackage(args);

ListVariables​

ListVariables provides users with the ability to parse KCL program and get all variables by specs.

Example

The content of schema.k is

schema AppConfig:
replicas: int

app: AppConfig {
replicas: 2
}

C# Code

using KclLib.API;

var api = new API();
var args = new ListVariablesArgs();
var path = "schema.k";
args.Files.Add(path);
var result = api.ListVariables(args);

ListOptions​

ListOptions provides users with the ability to parse KCL program and get all option information.

Example

The content of options.k is

a = option("key1")
b = option("key2", required=True)
c = {
metadata.key = option("metadata-key")
}

C# Code

using KclLib.API;

var path = "options.k";
var args = new ParseProgramArgs();
args.Paths.Add(path);
var result = new API().ListOptions(args);

GetSchemaTypeMapping​

Get schema type mapping defined in the program.

Example

The content of schema.k is

schema AppConfig:
replicas: int

app: AppConfig {
replicas: 2
}

C# Code

using KclLib.API;

var path = "schema.k";
var execArgs = new ExecProgramArgs();
execArgs.KFilenameList.Add(path);
var args = new GetSchemaTypeMappingArgs();
args.ExecArgs = execArgs;
var result = new API().GetSchemaTypeMapping(args);

GetSchemaTypeMappingUnderPath​

Get schema type mapping defined in the program and its dependency packages, keyed by package name. Different from GetSchemaTypeMapping, schemas imported from external dependency packages are keyed under their own package name instead of being flattened into __main__.

Example

C# Code

using KclLib.API;

var root = Path.GetFullPath("test_data/get_schema_ty_under_path");
var execArgs = new ExecProgramArgs();
execArgs.KFilenameList.Add(Path.Combine(root, "aaa"));
execArgs.ExternalPkgs.Add(new ExternalPkg { PkgName = "bbb", PkgPath = Path.Combine(root, "bbb") });
var args = new GetSchemaTypeMappingArgs();
args.ExecArgs = execArgs;
var result = new API().GetSchemaTypeMappingUnderPath(args);
var bbbSchemas = result.SchemaTypeMapping["bbb"].SchemaType.ToDictionary(s => s.SchemaName);

OverrideFile​

Override KCL file with arguments. See https://www.kcl-lang.io/docs/user_docs/guides/automation for more override spec guide.

Example

The content of main.k is

a = 1

b = {
"a": 1
"b": 2
}

C# Code

using KclLib.API;

var args = new OverrideFileArgs
{
File = "main.k",
};
args.Specs.Add("b.a=2");
var result = new API().OverrideFile(args);

FormatCode​

Format the code source.

Example

C# Code

using KclLib.API;

string sourceCode = "schema Person:\n" + " name: str\n" + " age: int\n" + " check:\n"
+ " 0 < age < 120\n";
string expectedFormattedCode = "schema Person:\n" + " name: str\n" + " age: int\n\n" + " check:\n"
+ " 0 < age < 120\n\n";
var api = new API();
var args = new FormatCodeArgs();
args.Source = sourceCode;
var result = api.FormatCode(args);

FormatPath​

Format KCL file or directory path contains KCL files and returns the changed file paths.

Example

The content of format_path.k is

schema Person:
name: str
age: int

check:
0 < age < 120

C# Code

using KclLib.API;

var api = new API();
var args = new FormatPathArgs();
var path = "format_path.k";
args.Path = path;
var result = api.FormatPath(args);

LintPath​

Lint files and return error messages including errors and warnings.

Example

The content of lint_path.k is

import math

a = 1

C# Code

using KclLib.API;

var path = "lint_path.k"
var args = new LintPathArgs();
args.Paths.Add(path);
var result = new API().LintPath(args);
bool foundWarning = result.Results.Any(warning => warning.Contains("Module 'math' imported but unused"));

ValidateCode​

Validate code using schema and JSON/YAML data strings.

Example

C# Code

using KclLib.API;

string code = @"
schema Person:
name: str
age: int
check:
0 < age < 120
";
string data = "{\"name\": \"Alice\", \"age\": 10}";
var args = new ValidateCodeArgs
{
Code = code,
Data = data,
Format = "json"
};
var result = new API().ValidateCode(args);

Rename​

Rename all the occurrences of the target symbol in the files. This API will rewrite files if they contain symbols to be renamed. Return the file paths that got changed.

Example

The content of main.k is

a = 1
b = a

C# Code

using KclLib.API;

RenameArgs args = RenameArgs.newBuilder().setPackageRoot(".").setSymbolPath("a")
.addFilePaths("main.k").setNewName("a2").build();
API apiInstance = new API();
RenameResult result = apiInstance.rename(args);

RenameCode​

Rename all the occurrences of the target symbol and return the modified code if any code has been changed. This API won't rewrite files but return the changed code.

Example

C# Code

using KclLib.API;

var args = new RenameCodeArgs
{
PackageRoot = "/mock/path",
SymbolPath = "a",
SourceCodes = { { "/mock/path/main.k", "a = 1\nb = a" } },
NewName = "a2"
};
var result = new API().RenameCode(args);

Test​

Test KCL packages with test arguments.

Example

C# Code

using KclLib.API;

var pkg = Path.Combine(parentDirectory, "test_data", "testing");
var args = new TestArgs();
args.PkgList.Add(pkg + "/...");
var result = new API().Test(args);

LoadSettingsFiles​

Load the setting file config defined in kcl.yaml

Example

The content of kcl.yaml is

kcl_cli_configs:
strict_range_check: true
kcl_options:
- key: key
value: value

C# Code

using KclLib.API;

var workDir = ".";
var settingsFile = "kcl.yaml";
var args = new LoadSettingsFilesArgs
{
WorkDir = workDir,
};
args.Files.Add(settingsFile);
var result = new API().LoadSettingsFiles(args);

UpdateDependencies​

Download and update dependencies defined in the kcl.mod file and return the external package name and location list.

Example

The content of module/kcl.mod is

[package]
name = "mod_update"
edition = "0.0.1"
version = "0.0.1"

[dependencies]
helloworld = { oci = "oci://ghcr.io/kcl-lang/helloworld", tag = "0.1.0" }
flask = { git = "https://github.com/kcl-lang/flask-demo-kcl-manifests", commit = "ade147b" }

C# Code

using KclLib.API;

var manifestPath = "module";
var args = new UpdateDependenciesArgs { ManifestPath = manifestPath };
var result = new API().UpdateDependencies(args);

Call ExecProgram with external dependencies

Example

The content of module/kcl.mod is

[package]
name = "mod_update"
edition = "0.0.1"
version = "0.0.1"

[dependencies]
helloworld = { oci = "oci://ghcr.io/kcl-lang/helloworld", tag = "0.1.0" }
flask = { git = "https://github.com/kcl-lang/flask-demo-kcl-manifests", commit = "ade147b" }

The content of module/main.k is

import helloworld
import flask

a = helloworld.The_first_kcl_program

C# Code

using KclLib.API;

API api = new API();

var manifestPath = "module";
var testFile = Path.Combine(manifestPath, "main.k");
var updateArgs = new UpdateDependenciesArgs { ManifestPath = manifestPath };
var depResult = new API().UpdateDependencies(updateArgs);
var execArgs = new ExecProgramArgs();
execArgs.KFilenameList.Add(testFile);
execArgs.ExternalPkgs.AddRange(depResult.ExternalPkgs);
var execResult = new API().ExecProgram(execArgs);

GetVersion​

Return the KCL service version information.

Example

C# Code

using KclLib.API;

var result = new API().GetVersion(new GetVersionArgs());

(The exact version / checksum / git_sha values vary per release; assert only on non-empty.)

Ping​

Round-trip a value through the dispatcher.

Example

using KclLib.API;

var result = new API().Ping(new PingArgs { Value = "hello" });
Console.WriteLine(result.Value); // -> "hello"

ListMethod​

List the KCL service method names supported by the underlying runtime.

Example

using KclLib.API;

foreach (var name in new API().ListMethod().MethodNameList)
{
Console.WriteLine(name);
}

Notes​

The legacy BuildProgram and ExecArtifact RPCs were removed from spec/spec.proto in v0.13.0 (see lib commit 815acac); they are no longer recognised by the KclLib.API.API dispatcher. If you previously called api.BuildProgram(...) or api.ExecArtifact(...), switch to api.ExecProgram(...).