> ## Documentation Index
> Fetch the complete documentation index at: https://mintlify.com/iii-hq/sdk/llms.txt
> Use this file to discover all available pages before exploring further.

# Functions

> Register and handle function invocations

## Overview

Functions are the core building blocks of III applications. A function is a piece of code that can be invoked remotely by other workers or triggers.

## Registering Functions

### register\_function

Register a function with the default configuration.

```rust theme={null}
pub fn register_function<F, Fut>(&self, id: impl Into<String>, handler: F)
where
    F: Fn(Value) -> Fut + Send + Sync + 'static,
    Fut: std::future::Future<Output = Result<Value, IIIError>> + Send + 'static
```

<ParamField path="id" type="impl Into<String>" required>
  Unique identifier for the function
</ParamField>

<ParamField path="handler" type="F" required>
  Async function that processes input and returns a result. The handler receives a `serde_json::Value` and must return `Result<Value, IIIError>`.
</ParamField>

**Example:**

```rust theme={null}
use iii_sdk::{III, IIIError};
use serde_json::{json, Value};

let iii = III::new("ws://localhost:49134");

iii.register_function("greet", |input: Value| async move {
    let name = input.get("name")
        .and_then(|v| v.as_str())
        .unwrap_or("World");
    
    Ok(json!({
        "greeting": format!("Hello, {}!", name)
    }))
});

iii.connect().await?;
```

### register\_function\_with\_description

Register a function with a description.

```rust theme={null}
pub fn register_function_with_description<F, Fut>(
    &self,
    id: impl Into<String>,
    description: impl Into<String>,
    handler: F,
)
where
    F: Fn(Value) -> Fut + Send + Sync + 'static,
    Fut: std::future::Future<Output = Result<Value, IIIError>> + Send + 'static
```

<ParamField path="id" type="impl Into<String>" required>
  Unique identifier for the function
</ParamField>

<ParamField path="description" type="impl Into<String>" required>
  Human-readable description of what the function does
</ParamField>

<ParamField path="handler" type="F" required>
  Async function handler
</ParamField>

**Example:**

```rust theme={null}
iii.register_function_with_description(
    "user.create",
    "Creates a new user in the system",
    |input: Value| async move {
        // Handler implementation
        Ok(json!({ "id": "user-123" }))
    }
);
```

### register\_function\_with

Register a function with full configuration options.

```rust theme={null}
pub fn register_function_with<F, Fut>(
    &self,
    message: RegisterFunctionMessage,
    handler: F,
)
where
    F: Fn(Value) -> Fut + Send + Sync + 'static,
    Fut: std::future::Future<Output = Result<Value, IIIError>> + Send + 'static
```

<ParamField path="message" type="RegisterFunctionMessage" required>
  Complete function registration message with all metadata
</ParamField>

<ParamField path="handler" type="F" required>
  Async function handler
</ParamField>

**Example:**

```rust theme={null}
use iii_sdk::{III, RegisterFunctionMessage};
use serde_json::json;

let message = RegisterFunctionMessage {
    id: "analytics.track".to_string(),
    description: Some("Track an analytics event".to_string()),
    request_format: Some(json!({
        "type": "object",
        "properties": {
            "event": { "type": "string" },
            "userId": { "type": "string" }
        }
    })),
    response_format: Some(json!({
        "type": "object",
        "properties": {
            "tracked": { "type": "boolean" }
        }
    })),
    metadata: None,
    invocation: None,
};

iii.register_function_with(message, |input| async move {
    // Implementation
    Ok(json!({ "tracked": true }))
});
```

## HTTP Functions

HTTP functions are proxy functions that invoke external HTTP endpoints.

### register\_http\_function

Register a function that proxies to an HTTP endpoint.

```rust theme={null}
pub fn register_http_function(
    &self,
    id: impl Into<String>,
    config: HttpInvocationConfig,
) -> Result<HttpFunctionRef, IIIError>
```

<ParamField path="id" type="impl Into<String>" required>
  Unique identifier for the function
</ParamField>

<ParamField path="config" type="HttpInvocationConfig" required>
  HTTP configuration including URL, method, headers, and authentication
</ParamField>

<ResponseField name="HttpFunctionRef" type="Result<HttpFunctionRef, IIIError>">
  Reference that can be used to unregister the function
</ResponseField>

**Example:**

```rust theme={null}
use iii_sdk::{III, HttpInvocationConfig, HttpMethod};
use std::collections::HashMap;

let iii = III::new("ws://localhost:49134");

let mut headers = HashMap::new();
headers.insert("Content-Type".to_string(), "application/json".to_string());

let http_fn = iii.register_http_function(
    "external.webhook",
    HttpInvocationConfig {
        url: "https://api.example.com/webhook".to_string(),
        method: HttpMethod::Post,
        timeout_ms: Some(30000),
        headers,
        auth: None,
    }
)?;

iii.connect().await?;

// Later, unregister the function
http_fn.unregister();
```

## Function Context

Every function handler runs within a context that provides logging and tracing capabilities.

### Accessing Context

Use `get_context()` to access the current function's context:

```rust theme={null}
use iii_sdk::{III, get_context};
use serde_json::{json, Value};

iii.register_function("process", |input: Value| async move {
    let ctx = get_context();
    
    // Log messages
    ctx.logger.info("Processing started", None);
    ctx.logger.debug("Input data", Some(input.clone()));
    
    // Your logic here
    let result = json!({ "status": "completed" });
    
    ctx.logger.info("Processing completed", Some(result.clone()));
    
    Ok(result)
});
```

### Context Structure

The `Context` struct provides:

```rust theme={null}
pub struct Context {
    pub logger: Logger,
    pub span: Option<tracing::Span>,
}
```

* `logger`: Logger instance scoped to the current function
* `span`: Active tracing span (when `otel` feature is enabled)

## Function Discovery

### list\_functions

List all registered functions in the engine.

```rust theme={null}
pub async fn list_functions(&self) -> Result<Vec<FunctionInfo>, IIIError>
```

<ResponseField name="Vec<FunctionInfo>" type="Result<Vec<FunctionInfo>, IIIError>">
  List of all registered functions with their metadata
</ResponseField>

**Example:**

```rust theme={null}
let functions = iii.list_functions().await?;

for func in functions {
    println!("Function: {}", func.function_id);
    if let Some(desc) = func.description {
        println!("  Description: {}", desc);
    }
}
```

### on\_functions\_available

Subscribe to notifications when functions become available.

```rust theme={null}
pub fn on_functions_available<F>(&self, callback: F) -> FunctionsAvailableGuard
where
    F: Fn(Vec<FunctionInfo>) + Send + Sync + 'static
```

<ParamField path="callback" type="F" required>
  Callback invoked whenever functions are registered or updated
</ParamField>

<ResponseField name="FunctionsAvailableGuard" type="FunctionsAvailableGuard">
  Guard that automatically unsubscribes when dropped
</ResponseField>

**Example:**

```rust theme={null}
let _guard = iii.on_functions_available(|functions| {
    println!("Functions updated: {} available", functions.len());
    for func in functions {
        println!("  - {}", func.function_id);
    }
});

// Guard keeps subscription active
// Drops when it goes out of scope
```

## Types

### RegisterFunctionMessage

```rust theme={null}
pub struct RegisterFunctionMessage {
    pub id: String,
    pub description: Option<String>,
    pub request_format: Option<Value>,
    pub response_format: Option<Value>,
    pub metadata: Option<Value>,
    pub invocation: Option<HttpInvocationConfig>,
}
```

### HttpInvocationConfig

```rust theme={null}
pub struct HttpInvocationConfig {
    pub url: String,
    pub method: HttpMethod,
    pub timeout_ms: Option<u64>,
    pub headers: HashMap<String, String>,
    pub auth: Option<HttpAuthConfig>,
}
```

### HttpMethod

```rust theme={null}
pub enum HttpMethod {
    Get,
    Post,
    Put,
    Patch,
    Delete,
}
```

### FunctionInfo

```rust theme={null}
pub struct FunctionInfo {
    pub function_id: String,
    pub description: Option<String>,
    pub request_format: Option<Value>,
    pub response_format: Option<Value>,
    pub metadata: Option<Value>,
}
```

## See Also

* [Invocation API](/rust/api/invocation) - Call registered functions
* [Context API](/rust/api/context) - Access function context and logging
* [Triggers API](/rust/api/triggers) - Automatically invoke functions based on events
