Skip to content

Build an agent

Tools & layers

Tools are the boundary between model suggestions and application effects. Effect AI owns their schemas and handler Layers; your application owns resource access and the meaning of each action. Yielded Agent validates calls, applies policy, and runs bounded batches.

import {
import Effect
Effect
,
import Schema
Schema
} from "effect";
import {
import Tool
Tool
,
import Toolkit
Toolkit
} from "effect/ai";
const
const Search: Tool.Tool<"search_activities", {
readonly parameters: Schema.Struct<{
readonly city: Schema.String;
}>;
readonly success: Schema.$Array<Schema.String>;
readonly failure: Schema.Never;
readonly failureMode: "error";
}, never>
Search
=
import Tool
Tool
.
const make: <"search_activities", Schema.Struct<{
readonly city: Schema.String;
}>, Schema.$Array<Schema.String>, Schema.Never, undefined, []>(name: "search_activities", options?: {
readonly description?: string | undefined;
readonly parameters?: Schema.Struct<{
readonly city: Schema.String;
}> | undefined;
readonly success?: Schema.$Array<Schema.String> | undefined;
readonly failure?: Schema.Never | undefined;
readonly failureMode?: undefined;
readonly dependencies?: [] | undefined;
readonly needsApproval?: Tool.NeedsApproval<...> | undefined;
readonly toModelOutput?: ((result: readonly string[]) => ReadonlyArray<ToolModelOutputPart>) | undefined;
} | undefined) => Tool.Tool<...>

Creates a user-defined tool with the specified name and configuration.

Details

This is the primary constructor for creating custom tools that AI models can call. The tool definition includes parameter validation, success/failure schemas, and optional service dependencies.

If a tool accepts no parameters but still needs an explicit empty object schema, use

EmptyParams

.

Example (Creating a tool without parameters)

import { Schema } from "effect"
import { Tool } from "effect/ai"
// Simple tool with no parameters
const GetCurrentTime = Tool.make("GetCurrentTime", {
description: "Returns the current timestamp",
success: Schema.Number
})
GetCurrentTime.name // => "GetCurrentTime"

@stability ― unstable

@category ― constructors

@since ― 4.0.0

make
("search_activities", {
description?: string | undefined

An optional description explaining what the tool does.

description
: "Find activities in a city.",
parameters?: Schema.Struct<{
readonly city: Schema.String;
}> | undefined

Schema defining the parameters this tool accepts.

parameters
:
import Schema
Schema
.
function Struct<{
readonly city: Schema.String;
}>(fields: {
readonly city: Schema.String;
}): Schema.Struct<{
readonly city: Schema.String;
}>

Defines a struct schema from a map of field schemas.

Details

Each field value is a schema. Use

optionalKey

or

optional

to mark fields as optional, and

mutableKey

to mark them as mutable.

The resulting schema's Type is a readonly object type with the fields' decoded types. The Encoded form mirrors the field schemas' encoded types. Declared fields may be inherited and are copied to own properties in the output. The __proto__ field is accepted only when it is an own property. Parsing does not guarantee that output keys retain their input order.

Example (Defining a basic struct)

import { Schema } from "effect"
const Person = Schema.Struct({
name: Schema.String,
age: Schema.Number,
email: Schema.optionalKey(Schema.String)
})
// { readonly name: string; readonly age: number; readonly email?: string }
type Person = typeof Person.Type
Schema.decodeUnknownSync(Person)({ name: "Alice", age: 30 }) // => { name: "Alice", age: 30 }

@stability ― stable

@category ― constructors

@since ― 3.10.0

Struct
({
city: Schema.String
city
:
import Schema
Schema
.
const String: Schema.String

Type-level representation of

String

.

Schema for string values. Validates that the input is typeof "string".

@stability ― stable

@category ― models

@since ― 4.0.0

@stability ― stable

@category ― schemas

@since ― 4.0.0

String
}),
success?: Schema.$Array<Schema.String> | undefined

Schema for successful tool execution results.

success
:
import Schema
Schema
.
Array<Schema.String>(self: Schema.String): Schema.$Array<Schema.String>
export Array

Defines a ReadonlyArray schema for a given element schema.

Example (Defining an array of strings)

import { Schema } from "effect"
const schema = Schema.Array(Schema.String)
Schema.decodeUnknownSync(schema)(["a", "b", "c"]) // => ["a", "b", "c"]

@stability ― stable

@category ― constructors

@since ― 4.0.0

Array
(
import Schema
Schema
.
const String: Schema.String

Type-level representation of

String

.

Schema for string values. Validates that the input is typeof "string".

@stability ― stable

@category ― models

@since ― 4.0.0

@stability ― stable

@category ― schemas

@since ― 4.0.0

String
),
});
const
const TravelTools: Toolkit.Toolkit<{
readonly search_activities: Tool.Tool<"search_activities", {
readonly parameters: Schema.Struct<{
readonly city: Schema.String;
}>;
readonly success: Schema.$Array<Schema.String>;
readonly failure: Schema.Never;
readonly failureMode: "error";
}, never>;
}>
TravelTools
=
import Toolkit
Toolkit
.
const make: <[Tool.Tool<"search_activities", {
readonly parameters: Schema.Struct<{
readonly city: Schema.String;
}>;
readonly success: Schema.$Array<Schema.String>;
readonly failure: Schema.Never;
readonly failureMode: "error";
}, never>]>(tools_0: Tool.Tool<"search_activities", {
readonly parameters: Schema.Struct<{
readonly city: Schema.String;
}>;
readonly success: Schema.$Array<Schema.String>;
readonly failure: Schema.Never;
readonly failureMode: "error";
}, never>) => Toolkit.Toolkit<...>

Creates a new toolkit from the specified tools.

Details

This is the primary constructor for creating toolkits. It accepts multiple tools and organizes them into a toolkit that can be provided to AI language models.

Example (Creating a toolkit)

import { Effect, Schema } from "effect"
import { Tool, Toolkit } from "effect/ai"
const GetCurrentTime = Tool.make("GetCurrentTime", {
description: "Get the current timestamp",
success: Schema.Number
})
const GetWeather = Tool.make("get_weather", {
description: "Get weather information",
parameters: Schema.Struct({ location: Schema.String }),
success: Schema.Struct({
temperature: Schema.Number,
condition: Schema.String
})
})
const toolkit = Toolkit.make(GetCurrentTime, GetWeather)
const ready = toolkit.pipe(Effect.provide(toolkit.toLayer({
GetCurrentTime: () => Effect.succeed(0),
get_weather: () => Effect.succeed({ temperature: 20, condition: "clear" })
})))
Object.keys((await Effect.runPromise(ready)).tools) // => ["GetCurrentTime", "get_weather"]

@stability ― unstable

@category ― constructors

@since ― 4.0.0

make
(
const Search: Tool.Tool<"search_activities", {
readonly parameters: Schema.Struct<{
readonly city: Schema.String;
}>;
readonly success: Schema.$Array<Schema.String>;
readonly failure: Schema.Never;
readonly failureMode: "error";
}, never>
Search
);
const
const TravelToolsLive: Layer<Tool.Handler<"search_activities">, never, never>
TravelToolsLive
=
const TravelTools: Toolkit.Toolkit<{
readonly search_activities: Tool.Tool<"search_activities", {
readonly parameters: Schema.Struct<{
readonly city: Schema.String;
}>;
readonly success: Schema.$Array<Schema.String>;
readonly failure: Schema.Never;
readonly failureMode: "error";
}, never>;
}>
TravelTools
.
Toolkit<{ readonly search_activities: Tool<"search_activities", { readonly parameters: Struct<{ readonly city: String; }>; readonly success: $Array<String>; readonly failure: Never; readonly failureMode: "error"; }, never>; }>.toLayer<{
search_activities: ({ city }: {
readonly city: string;
}) => Effect.Effect<string[], never, never>;
}, never, never>(build: {
search_activities: ({ city }: {
readonly city: string;
}) => Effect.Effect<string[], never, never>;
} | Effect.Effect<{
search_activities: ({ city }: {
readonly city: string;
}) => Effect.Effect<string[], never, never>;
}, never, never>): Layer<Tool.Handler<"search_activities">, never, never>

Converts a toolkit into a Layer containing handlers for each tool in the toolkit.

toLayer
({
search_activities: ({ city }: {
readonly city: string;
}) => Effect.Effect<string[], never, never>
search_activities
: ({
city: string
city
}) =>
import Effect
Effect
.
const succeed: <string[]>(value: string[]) => Effect.Effect<string[], never, never>

Creates an Effect that always succeeds with a given value.

When to use

Use when an effect should complete successfully with a specific value without any errors or external dependencies.

Example (Creating a successful effect)

import { Effect } from "effect"
// Creating an effect that represents a successful scenario
//
// ┌─── Effect<number, never, never>
// ▼
const success = Effect.succeed(42)
Effect.runSync(success) // => 42

@see ― fail to create an effect that represents a failure.

@stability ― stable

@category ― constructors

@since ― 2.0.0

succeed
(
city: string
city
=== "Lisbon" ? ["Riverside walk", "Food market"] : []),
});

Set the Agent’s toolkit to TravelTools and provide TravelToolsLive alongside the model Layer. Replace the sample data with an application service; its errors and dependencies remain visible in Effect. The travel-planner snippets show complete composition.

The engine validates the complete response before starting application handlers. Calls execute with bounded concurrency; progress can arrive in completion order, while committed results retain the model’s declaration order. The next model request sees the complete batch.

Use execution budgets to bound turns, calls, output, and concurrency. Large results are bounded before they enter history or the next prompt.

A declared failure Schema describes expected errors. By default, failureMode: "error" propagates those errors and fails the Run. Set failureMode: "return" when the model should receive a failed tool result and try another approach. Invalid native tool arguments can then return a validation failure without starting the handler. Defects, interruption, and invalid result encoding still fail.

Treat an empty search result as successful data, such as an empty array.

Install RunToolAuthorization for action-time policy. It checks executable application calls before handlers start, including programmatic calls from Code Mode. Durable recovery checks authorization again for unfinished calls. The host must supply actual caller authority; model-provided identifiers are untrusted. Handlers still enforce access to the specific resources they use.

Effect AI tools can require approval. A pending approval prevents the handler from starting; a durable host retains the request and accepts an authorized resolution later. An approval is a decision about the proposed call, not permission to bypass current resource authorization. Never infer approval from model prose.

ToolExposure limits declarations sent to a model, and ToolDiscovery lets it search an eligible catalogue. Host visibility and inherited subagent grants constrain both discovery and execution. Selection changes what the model sees; it grants no additional authority. Use this when a large toolkit would crowd out task context. ToolDiscovery.make provides bounded literal search. For custom ranking, define a native Tool with DiscoveryTool and ToolExecutionClass: "readonly", read CurrentToolCatalog, and use Schema.Struct({ toolNames: ToolNames }) as its success schema.

Unannotated tools have execution class "uncertain". If an external effect may have happened but its result was not recorded, durable recovery records Unknown and does not automatically repeat it. Resolve the outcome from external evidence before continuing.

Declare "readonly" or "idempotent" only when the handler satisfies that contract. A DurableStep can retain named results across retries, but its body may execute again. Use the external system’s idempotency or reconciliation API; Steps do not guarantee exactly-once effects. See durability.

Use effect/ai/McpClient for MCP connections and discovery. Acquire the client in a Scope and bind selected remote calls through ordinary Toolkit handlers. Its callTool operation can decode structured output with the application’s Schema; declare McpClientError from effect/ai/McpClientError as the Tool’s failure schema when returning remote failures to the model. Keep the client Scope open while its tool handlers can run, and configure transport and discovery limits through Effect’s APIs.

Remote calls follow the same authorization, approval, budgets, and uncertainty rules as other tools. Leave their execution class "uncertain" unless the application can establish a stronger contract; server hints alone do not establish replay safety.

Use subagents for delegation, browser tools for web interaction, or Code Mode for a bounded program over several tools.