Skip to content

Tool

Definitions and helpers for tools that AI models can request during a workflow.

A tool names an operation, describes the parameters it accepts, declares successful and failed results, and can require approval before execution. This module supports tools defined by the application, tools built into a provider, and dynamic tools whose schema is known only at runtime. It also includes the shared types and conversion helpers needed by language-model requests, tool handlers, and provider integrations.

59 exports Added in v4.0.0 Source

Constructors

dynamic

Added in v4.0.0 Source

Creates a dynamic tool that can accept either an Effect Schema or a raw JSON Schema for its parameters.

When to use

Use when you do not know a tool schema at compile time, such as MCP tools discovered at runtime or tools from external configurations.

Details

- When parameters is an Effect Schema: full type safety with validation - When parameters is a JSON Schema: handler receives unknown, no validation

Signature

declare const dynamic: <
Name extends string,
Options extends {
readonly description?: string;
readonly failure?: Schema.Constraint;
readonly failureMode?: FailureMode;
readonly needsApproval?: NeedsApproval<any>;
readonly parameters?: Schema.Constraint | JsonSchema.JsonSchema;
readonly success?: Schema.Constraint;
},
>(
name: Name,
options?: Options,
) => Dynamic<
Name,
{
readonly failure: Options extends {
readonly failure: infer F extends Schema.Constraint;
}
? F
: typeof Schema.Never;
readonly failureMode: Options extends {
readonly failureMode: infer M extends FailureMode;
}
? M
: "error";
readonly parameters: Options extends {
readonly parameters: infer P;
}
? P extends Schema.Constraint
? P
: P extends JsonSchema.JsonSchema
? P
: typeof Schema.Unknown
: typeof Schema.Unknown;
readonly success: Options extends {
readonly success: infer S extends Schema.Constraint;
}
? S
: typeof Schema.Unknown;
}
>;

make

Added in v4.0.0 Source

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.

Signature

declare function make<
Name extends string,
Parameters extends Constraint = EmptyParams,
Success extends Constraint = Void,
Failure extends Constraint = Never,
Mode extends FailureMode | undefined = undefined,
Dependencies extends Array<Key<any, any> | Key<never, any>> = [],
>(
name: Name,
options?: {
readonly dependencies?: Dependencies;
readonly description?: string;
readonly failure?: Failure;
readonly failureMode?: Mode;
readonly needsApproval?: NeedsApproval<Parameters>;
readonly parameters?: Parameters;
readonly success?: Success;
},
): Tool<
Name,
{
readonly failure: Failure;
readonly failureMode: Mode extends undefined ? "error" : Mode;
readonly parameters: Parameters;
readonly success: Success;
},
Identifier<Dependencies[number]>
>;

Creates a provider-defined tool which leverages functionality built into a large language model provider (e.g. web search, code execution).

Details

These tools are executed by the large language model provider rather than by your application. However, they can optionally require custom handlers implemented in your application to process provider generated results.

Signature

declare function providerDefined<
Identifier extends `${string}.${string}`,
Name extends string,
Args extends Constraint = Void,
Parameters extends Constraint = Void,
Success extends Constraint = Void,
Failure extends Constraint = Never,
RequiresHandler extends boolean = false,
>(options: {
readonly args?: Args;
readonly customName: Name;
readonly failure?: Failure;
readonly id: Identifier;
readonly parameters?: Parameters;
readonly providerName: string;
readonly requiresHandler?: RequiresHandler;
readonly success?: Success;
}): <Mode extends FailureMode | undefined = undefined>(
args: RequiresHandler extends true
? {
[K in string | number | symbol]: Args["Encoded"] &
{
readonly failureMode?: Mode;
}[K];
}
: { [K in string | number | symbol]: Args["Encoded"][K] },
) => ProviderDefined<
Identifier,
Name,
{
readonly args: Args;
readonly failure: Failure;
readonly failureMode: Mode extends undefined ? "error" : Mode;
readonly parameters: Parameters;
readonly success: Success;
},
RequiresHandler
>;

Converting

Generates a JSON Schema from an Effect Schema.

Details

If a CodecTransformer is supplied, the transformed schema's JSON Schema is returned. Otherwise, the schema is converted with Schema.toJsonSchemaDocument and any generated definitions are attached as $defs.

Signature

declare function getJsonSchemaFromSchema<S extends Constraint>(
schema: S,
options?: {
readonly transformer?: CodecTransformer;
},
): JsonSchema;

Getters

Extracts the description from a tool's metadata.

Details

Returns the tool's description if explicitly set, otherwise attempts to extract it from the parameter schema's AST annotations.

Signature

declare function getDescription<Tool extends Any>(tool: Tool): string | undefined;

Generates a JSON Schema for a tool.

Details

This function creates a JSON Schema representation that can be used by large language models to indicate the structure and type of the parameters that a given tool call should receive.

May accept an optional CodecTransformer which can be used to transform the tool parameter schema so that the resultant JSON schema for the tool call parameters are in a format that conforms to any provider-specific constraints.

Signature

declare function getJsonSchema<Tool extends Any>(
tool: Tool,
options?: {
readonly transformer?: CodecTransformer;
},
): JsonSchema;

Returns the strict mode setting for a tool, or undefined if not set.

When to use

Use to inspect the per-tool strict JSON Schema override attached through Tool.Strict.

Gotchas

undefined means no per-tool override is set. It is distinct from false; provider or global configuration determines the final behavior.

See

  • Strict for the annotation read by this helper

Signature

declare function getStrictMode<T extends Any>(tool: T): boolean | undefined;

Guards

isDynamic

Added in v4.0.0 Source

Type guard to check if a value is a dynamic tool.

Signature

declare function isDynamic(u: unknown): u is Dynamic<string, any, never>;

Type guard to check if a value is a provider-defined tool.

Signature

declare function isProviderDefined(
u: unknown,
): u is ProviderDefined<`${string}.${string}`, string, any, false>;

Type guard to check if a value is a user-defined tool.

Signature

declare function isUserDefined(u: unknown): u is Tool<string, any, any>;

Models

Dynamic interface

Added in v4.0.0 Source

A dynamic tool is a tool where the schema may not be known at compile time.

Details

Dynamic tools support two modes: - Effect Schema mode: Full type safety with validation (like Tool.make) - JSON Schema mode: Raw JSON Schema for the model, handler receives unknown

This enables scenarios such as MCP tools discovered at runtime, user-defined functions loaded from external sources, or plugin systems.

Signature

interface Dynamic<
out Name extends string,
out Config extends {
readonly failure: Schema.Constraint;
readonly failureMode: FailureMode;
readonly parameters: Schema.Constraint | JsonSchema.JsonSchema;
readonly success: Schema.Constraint;
},
out Requirements = never,
> extends Tool<
Name,
{
readonly failure: Config["failure"];
readonly failureMode: Config["failureMode"];
readonly parameters: Config["parameters"] extends Schema.Constraint
? Config["parameters"]
: typeof Schema.Unknown;
readonly success: Config["success"];
},
Requirements
> {
readonly "~effect/ai/Tool/Dynamic": "~effect/ai/Tool/Dynamic";
readonly jsonSchema: Config["parameters"] extends Constraint ? undefined : JsonSchema;
}

FailureMode type

Added in v4.0.0 Source

The strategy used for handling errors returned from tool call handler execution.

Details

If set to "error" (the default), errors that occur during tool call handler execution will be returned in the error channel of the calling effect.

If set to "return", errors that occur during tool call handler execution will be captured and returned as part of the tool call result.

Signature

type FailureMode = "error" | "return";

Handler interface

Added in v4.0.0 Source

Represents an Tool that has been implemented within the application.

Signature

interface Handler<Name extends string> {
readonly _: typeof _;
readonly context: Context<never>;
readonly handler: (params: any, ctx: any) => Effect<any, any>;
readonly name: Name;
}

HandlerOutput type

Added in v4.0.0 Source

Tagged union for incremental handler output.

Details

When a tool handler returns a Stream, each emitted value is tagged as either: - Preliminary: An intermediate result representing progress - Final: The last result, which is the authoritative output

Signature

type HandlerOutput<Success> =
| {
readonly _tag: "Preliminary";
readonly value: Success;
}
| {
readonly _tag: "Final";
readonly value: Success;
};

HandlerResult interface

Added in v4.0.0 Source

Represents the result of calling the handler for a particular Tool.

Signature

interface HandlerResult<Tool extends Any> {
readonly encodedResult: unknown;
readonly isFailure: boolean;
readonly preliminary: boolean;
readonly result: Result<Tool>;
}

NameMapper

Added in v4.0.0 Source

Maps between a provider-defined tool name and the name given to the tool by the Effect AI SDK.

Details

The custom names used by the Effect AI SDK are to allow for toolkits which contain tools from multiple different providers that would otherwise have naming conflicts (i.e. "web_search") to instead use custom names (i.e. "OpenAiWebSearch").

Signature

declare class NameMapper<Tools extends ReadonlyArray<Any>> {
constructor<Tools extends readonly Array<Any>>(tools: Tools);
customNames: readonly Array<string>;
providerNames: readonly Array<string>;
getCustomName(providerName: string): string;
getProviderName(customName: string): string;
}

NeedsApproval type

Added in v4.0.0 Source

Specifies whether user approval is required before executing a tool.

Details

Can be: - boolean: Static approval requirement - NeedsApprovalFunction: Dynamic approval based on parameters/context

Signature

type NeedsApproval<Params extends Schema.Constraint> = boolean | NeedsApprovalFunction<Params>;

NeedsApprovalContext interface

Added in v4.0.0 Source

Context provided to the needsApproval function when dynamically determining if a tool requires user approval.

Signature

interface NeedsApprovalContext {
readonly messages: readonly Array<Message>;
readonly toolCallId: string;
}

Function type for dynamically determining if a tool requires approval.

Signature

type NeedsApprovalFunction<Params extends Schema.Constraint> = (
params: Params["Type"],
context: NeedsApprovalContext,
) => boolean | Effect.Effect<boolean>;

ProviderDefined interface

Added in v4.0.0 Source

A provider-defined tool is a tool which is built into a large language model provider (e.g. web search, code execution).

Details

These tools are executed by the large language model provider rather than by your application. However, they can optionally require custom handlers implemented in your application to process provider generated results.

Signature

interface ProviderDefined<
out Identifier extends `${string}.${string}`,
out Name extends string,
out Config extends {
readonly args: Schema.Constraint;
readonly failure: Schema.Constraint;
readonly failureMode: FailureMode;
readonly parameters: Schema.Constraint;
readonly success: Schema.Constraint;
},
out RequiresHandler extends boolean = false,
> extends Tool<
Name,
{
readonly failure: Config["failure"];
readonly failureMode: Config["failureMode"];
readonly parameters: Config["parameters"];
readonly success: Config["success"];
}
> {
readonly "~effect/ai/Tool/ProviderDefined": "~effect/ai/Tool/ProviderDefined";
readonly args: Config["args"]["Encoded"];
readonly argsSchema: Config["args"];
readonly id: Identifier;
readonly providerName: string;
readonly requiresHandler: RequiresHandler;
}

Tool interface

Added in v4.0.0 Source

A user-defined tool that language models can call to perform actions.

Details

Tools represent actionable capabilities that large language models can invoke to extend their functionality beyond text generation. Each tool has a defined schema for parameters, results, and failures.

Signature

interface Tool<
out Name extends string,
out Config extends {
readonly failure: Schema.Constraint;
readonly failureMode: FailureMode;
readonly parameters: Schema.Constraint;
readonly success: Schema.Constraint;
},
out Requirements = never,
> {
readonly "~effect/ai/Tool": {
readonly _Requirements: Covariant<Requirements>;
};
readonly annotations: Context<never>;
readonly description?: string;
readonly failureMode: FailureMode;
readonly failureSchema: Config["failure"];
readonly id: string;
readonly name: Name;
readonly needsApproval?: boolean | NeedsApprovalFunction<any>;
readonly parametersSchema: Config["parameters"];
readonly successSchema: Config["success"];
addDependency<Identifier, Service>(
tag: Key<Identifier, Service>,
): Tool<Name, Config, Requirements | Identifier>;
annotate<I, S>(tag: Key<I, S>, value: S): Tool<Name, Config, Requirements>;
annotateMerge<I>(context: Context<I>): Tool<Name, Config, Requirements>;
setFailure<FailureSchema extends Constraint>(
schema: FailureSchema,
): Tool<
Name,
{
readonly failure: FailureSchema;
readonly failureMode: Config["failureMode"];
readonly parameters: Config["parameters"];
readonly success: Config["success"];
},
Requirements
>;
setNeedsApproval(
needsApproval: NeedsApproval<Config["parameters"]>,
): Tool<Name, Config, Requirements>;
setParameters<ParametersSchema extends Constraint>(
schema: ParametersSchema,
): Tool<
Name,
{
readonly failure: Config["failure"];
readonly failureMode: Config["failureMode"];
readonly parameters: ParametersSchema;
readonly success: Config["success"];
},
Requirements
>;
setSuccess<SuccessSchema extends Constraint>(
schema: SuccessSchema,
): Tool<
Name,
{
readonly failure: Config["failure"];
readonly failureMode: Config["failureMode"];
readonly parameters: Config["parameters"];
readonly success: SuccessSchema;
},
Requirements
>;
}

Schemas

EmptyParams

Added in v4.0.0 Source

Schema for tools that accept no parameters.

When to use

Use when you need an explicit no-parameter parameters schema for a tool.

Details

This is Schema.Record(Schema.String, Schema.Never), representing an empty object parameter shape with no additional properties.

See

  • make for the tool constructor that defaults omitted parameters to this schema

Signature

declare const EmptyParams: EmptyParams;

EmptyParams interface

Added in v4.0.0 Source

Type of the EmptyParams schema used for tools with no parameters.

Details

It is a record schema with string keys and never values, so the generated parameter schema accepts an empty object shape with no properties.

Signature

interface EmptyParams extends $Record<Schema.String, Schema.Never> {
constructor(_: never);
}

Services

Destructive

Added in v4.0.0 Source

Annotation indicating whether a tool may perform destructive operations.

Details

This is emitted as the MCP destructiveHint; unannotated tools default to true, so annotate safe tools with false.

Signature

declare const Destructive: Reference<boolean>;

Idempotent

Added in v4.0.0 Source

Annotation indicating whether a tool can be called repeatedly with the same parameters without changing the result beyond the first call.

Details

This is emitted as the MCP idempotentHint; unannotated tools default to false.

Signature

declare const Idempotent: Reference<boolean>;

Meta

Added in v4.0.0 Source

Annotation for providing tool metadata for MCP.

Signature

declare class Meta extends Shape<"effect/ai/Tool/Meta", Record<string, unknown>, this> {
constructor(_: never);
}

OpenWorld

Added in v4.0.0 Source

Annotation indicating whether a tool may interact with arbitrary external data or systems.

Details

This is emitted as the MCP openWorldHint; unannotated tools default to true.

Signature

declare const OpenWorld: Reference<boolean>;

Readonly

Added in v4.0.0 Source

Annotation indicating whether a tool only reads data without making changes.

Details

This is emitted as the MCP readOnlyHint; unannotated tools default to false.

Signature

declare const Readonly: Reference<boolean>;

Strict

Added in v4.0.0 Source

Annotation controlling whether strict JSON schema mode is enabled for a tool.

Details

When true, providers that support strict mode will send strict: true to the model API (e.g. OpenAI's Structured Outputs).

When false, strict mode is disabled and strict: false is sent.

When undefined (default), the provider's global configuration determines the behavior (e.g. Config.strictJsonSchema for OpenAI).

Signature

declare const Strict: Reference<boolean | undefined>;

Title

Added in v4.0.0 Source

Annotation for providing a human-readable title for tools.

Signature

declare class Title extends Shape<"effect/ai/Tool/Title", string, this> {
constructor(_: never);
}

Type IDs

Runtime type identifier carried by dynamic tools.

Details

isDynamic uses this marker to distinguish tools whose schema may be provided at runtime from user-defined and provider-defined tools.

Signature

declare const DynamicTypeId: DynamicTypeId;

DynamicTypeId type

Added in v4.0.0 Source

Type-level representation of the dynamic tool runtime type identifier.

Signature

type DynamicTypeId = "~effect/ai/Tool/Dynamic";

Runtime type identifier carried by provider-defined tools.

Details

isProviderDefined uses this marker to distinguish tools that are built into an AI provider from user-defined and dynamic tools.

Signature

declare const ProviderDefinedTypeId: ProviderDefinedTypeId;

Type-level representation of the provider-defined tool runtime type identifier.

Signature

type ProviderDefinedTypeId = "~effect/ai/Tool/ProviderDefined";

TypeId

Added in v4.0.0 Source

Runtime type identifier carried by Effect AI tool values.

Details

The tool type guards use this marker, together with more specific markers, to distinguish user-defined, provider-defined, and dynamic tools.

Signature

declare const TypeId: TypeId;

TypeId type

Added in v4.0.0 Source

Type-level representation of the Effect AI tool runtime type identifier.

Signature

type TypeId = "~effect/ai/Tool";

Unsafe

Parses JSON text while rejecting prototype-pollution keys.

When to use

Use when you need a JSON parser that throws for invalid JSON or unsafe object shapes.

Gotchas

Invalid JSON throws through JSON.parse. Parsed objects containing an own __proto__ property or a dangerous constructor.prototype shape throw a SyntaxError.

Signature

declare function unsafeSecureJsonParse(text: string): unknown;

Utility Types

Any interface

Added in v4.0.0 Source

A type which represents any Tool.

Signature

interface Any extends Tool<
any,
{
readonly failure: Schema.Top;
readonly failureMode: FailureMode;
readonly parameters: Schema.Top;
readonly success: Schema.Top;
},
any
> {}

AnyDynamic interface

Added in v4.0.0 Source

A type which represents any dynamic Tool.

Signature

interface AnyDynamic extends Dynamic<
any,
{
readonly failure: Schema.Top;
readonly failureMode: FailureMode;
readonly parameters: Schema.Top | JsonSchema.JsonSchema;
readonly success: Schema.Top;
},
any
> {}

AnyProviderDefined interface

Added in v4.0.0 Source

A type which represents any provider-defined Tool.

Signature

interface AnyProviderDefined extends ProviderDefined<
any,
any,
{
readonly args: Schema.Top;
readonly failure: Schema.Top;
readonly failureMode: FailureMode;
readonly parameters: Schema.Top;
readonly success: Schema.Top;
},
any
> {}

Failure type

Added in v4.0.0 Source

A utility type to extract the type of the tool call result when it fails.

Signature

type Failure<T> =
T extends Tool<infer _Name, infer _Config, infer _Requirements>
? _Config["failure"]["Type"]
: never;

FailureEncoded type

Added in v4.0.0 Source

A utility type to extract the encoded type of the tool call result when it fails.

Signature

type FailureEncoded<T> =
T extends Tool<infer _Name, infer _Config, infer _Requirements>
? _Config["failure"]["Encoded"]
: never;

FailureResult type

Added in v4.0.0 Source

A utility type for the actual failure value that can appear in tool results. When failureMode is "return", this includes both user-defined failures and AiError.

Signature

type FailureResult<T> =
T extends Tool<infer _Name, infer _Config, infer _Requirements>
? _Config["failureMode"] extends "return"
? _Config["failure"]["Type"] | AiError.AiError
: _Config["failure"]["Type"]
: never;

FailureResultEncoded type

Added in v4.0.0 Source

The encoded version of FailureResult.

Signature

type FailureResultEncoded<T> =
T extends Tool<infer _Name, infer _Config, infer _Requirements>
? _Config["failureMode"] extends "return"
? _Config["failure"]["Encoded"] | AiError.AiErrorEncoded
: _Config["failure"]["Encoded"]
: never;

HandlerError type

Added in v4.0.0 Source

A utility type which represents the possible errors that can be raised by a tool call's handler.

Signature

type HandlerError<T> =
T extends Tool<infer _Name, infer _Config, infer _Requirements>
? _Config["failureMode"] extends "error"
? _Config["failure"]["Type"] | AiError.AiError
: never
: never;

HandlerServices type

Added in v4.0.0 Source

A utility type to extract the requirements of a Tool call handler.

Signature

type HandlerServices<T> =
T extends Tool<infer _Name, infer _Config, infer _Requirements>
? _Config["parameters"]["DecodingServices"] | ResultEncodingServices<T> | _Requirements
: never;

HandlersFor type

Added in v4.0.0 Source

A utility type to create a union of Handler types for all tools in a record.

Signature

type HandlersFor<Tools extends Record<string, Any>> = {
[Name in keyof Tools]: RequiresHandler<Tools[Name]> extends true
? Handler<Tools[Name]["name"]>
: never;
}[keyof Tools];

Name type

Added in v4.0.0 Source

A utility type to extract the Name type from an Tool.

Signature

type Name<T> = T extends Tool<infer _Name, infer _Config, infer _Requirements> ? _Name : never;

Parameters type

Added in v4.0.0 Source

A utility type to extract the type of the tool call parameters.

Signature

type Parameters<T> =
T extends Tool<infer _Name, infer _Config, infer _Requirements>
? _Config["parameters"]["Type"]
: never;

ParametersEncoded type

Added in v4.0.0 Source

A utility type to extract the encoded type of the tool call parameters.

Signature

type ParametersEncoded<T> =
T extends Tool<infer _Name, infer _Config, infer _Requirements>
? _Config["parameters"]["Encoded"]
: never;

ParametersSchema type

Added in v4.0.0 Source

A utility type to extract the schema for the parameters which an Tool must be called with.

Signature

type ParametersSchema<T> =
T extends Tool<infer _Name, infer _Config, infer _Requirements> ? _Config["parameters"] : never;

RequiresHandler type

Added in v4.0.0 Source

A utility type to determine if the specified tool requires a user-defined handler to be implemented.

Signature

type RequiresHandler<Tool extends Any> =
Tool extends ProviderDefined<infer _Name, infer _Config, infer _RequiresHandler>
? _RequiresHandler
: true;

Result type

Added in v4.0.0 Source

A utility type to extract the type of the tool call result whether it succeeds or fails.

Details

When failureMode is "return", the result may also be an AiError.

Signature

type Result<T> =
T extends Tool<infer _Name, infer _Config, infer _Requirements>
? _Config["failureMode"] extends "return"
? Success<T> | Failure<T> | AiError.AiError
: Success<T> | Failure<T>
: never;

A utility type to extract the requirements needed to decode the result of a Tool call.

Signature

type ResultDecodingServices<T> =
T extends Tool<infer _Name, infer _Config, infer _Requirements>
? _Config["success"]["DecodingServices"] | _Config["failure"]["DecodingServices"]
: never;

ResultEncoded type

Added in v4.0.0 Source

A utility type to extract the encoded type of the tool call result whether it succeeds or fails.

Details

When failureMode is "return", the result may also be an encoded AiError.

Signature

type ResultEncoded<T> =
T extends Tool<infer _Name, infer _Config, infer _Requirements>
? _Config["failureMode"] extends "return"
? SuccessEncoded<T> | FailureEncoded<T> | AiError.AiErrorEncoded
: SuccessEncoded<T> | FailureEncoded<T>
: never;

A utility type to extract the requirements needed to encode the result of a Tool call.

Signature

type ResultEncodingServices<T> =
T extends Tool<infer _Name, infer _Config, infer _Requirements>
? _Config["success"]["EncodingServices"] | _Config["failure"]["EncodingServices"]
: never;

Success type

Added in v4.0.0 Source

A utility type to extract the type of the tool call result when it succeeds.

Signature

type Success<T> =
T extends Tool<infer _Name, infer _Config, infer _Requirements>
? _Config["success"]["Type"]
: never;

SuccessEncoded type

Added in v4.0.0 Source

A utility type to extract the encoded type of the tool call result when it succeeds.

Signature

type SuccessEncoded<T> =
T extends Tool<infer _Name, infer _Config, infer _Requirements>
? _Config["success"]["Encoded"]
: never;

SuccessSchema type

Added in v4.0.0 Source

A utility type to extract the schema for the return type of a tool call when the tool call succeeds.

Signature

type SuccessSchema<T> =
T extends Tool<infer _Name, infer _Config, infer _Requirements> ? _Config["success"] : never;