Tool.ts
Tool.ts overview
Section titled “Tool.ts overview”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.
Since v4.0.0
Exports Grouped by Category
Section titled “Exports Grouped by Category”- annotations
- constructors
- converting
- getters
- guards
- models
- schemas
- type IDs
- unsafe
- utility types
- Any (interface)
- AnyDynamic (interface)
- AnyProviderDefined (interface)
- Failure (type alias)
- FailureEncoded (type alias)
- FailureResult (type alias)
- FailureResultEncoded (type alias)
- HandlerError (type alias)
- HandlerServices (type alias)
- HandlersFor (type alias)
- Name (type alias)
- Parameters (type alias)
- ParametersEncoded (type alias)
- ParametersSchema (type alias)
- RequiresHandler (type alias)
- Result (type alias)
- ResultDecodingServices (type alias)
- ResultEncoded (type alias)
- ResultEncodingServices (type alias)
- Success (type alias)
- SuccessEncoded (type alias)
- SuccessSchema (type alias)
annotations
Section titled “annotations”Destructive
Section titled “Destructive”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.
Example (Marking a tool as non-destructive)
import { Tool } from "effect/unstable/ai"
const safeTool = Tool.make("search_database").annotate(Tool.Destructive, false)Signature
declare const Destructive: Context.Reference<boolean>Since v4.0.0
Idempotent
Section titled “Idempotent”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.
Example (Marking a tool as idempotent)
import { Tool } from "effect/unstable/ai"
const idempotentTool = Tool.make("get_current_time").annotate(Tool.Idempotent, true)Signature
declare const Idempotent: Context.Reference<boolean>Since v4.0.0
Meta (class)
Section titled “Meta (class)”Annotation for providing tool metadata for MCP.
Example (Annotating MCP metadata)
import { Tool } from "effect/unstable/ai"
const myCalculatorUi = Tool.make("calculator_ui", {}).annotate(Tool.Meta, { ui: { resourceUri: "ui://example/calculator-ui" }})Signature
declare class MetaSince v4.0.0
OpenWorld
Section titled “OpenWorld”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.
Example (Disabling open-world access)
import { Tool } from "effect/unstable/ai"
const restrictedTool = Tool.make("internal_operation").annotate(Tool.OpenWorld, false)Signature
declare const OpenWorld: Context.Reference<boolean>Since v4.0.0
Readonly
Section titled “Readonly”Annotation indicating whether a tool only reads data without making changes.
Details
This is emitted as the MCP readOnlyHint; unannotated tools default to
false.
Example (Marking a tool as read-only)
import { Tool } from "effect/unstable/ai"
const readOnlyTool = Tool.make("get_user_info").annotate(Tool.Readonly, true)Signature
declare const Readonly: Context.Reference<boolean>Since v4.0.0
Strict
Section titled “Strict”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).
Example (Disabling strict JSON schema mode)
import { Tool } from "effect/unstable/ai"
const flexibleTool = Tool.make("search").annotate(Tool.Strict, false)Signature
declare const Strict: Context.Reference<boolean | undefined>Since v4.0.0
Title (class)
Section titled “Title (class)”Annotation for providing a human-readable title for tools.
Example (Annotating a tool title)
import { Tool } from "effect/unstable/ai"
const myTool = Tool.make("calculate_tip").annotate(Tool.Title, "Tip Calculator")Signature
declare class TitleSince v4.0.0
constructors
Section titled “constructors”dynamic
Section titled “dynamic”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
parametersis an Effect Schema: full type safety with validation - When
parametersis a JSON Schema: handler receivesunknown, no validation
Example (Creating a dynamic tool)
import { Schema } from "effect"import { Tool } from "effect/unstable/ai"
// With Effect Schema (typed parameters)const Calculator = Tool.dynamic("Calculator", { parameters: Schema.Struct({ operation: Schema.Literals(["add", "subtract"]), a: Schema.Number, b: Schema.Number }), success: Schema.Number})
// With JSON Schema (untyped parameters)const McpTool = Tool.dynamic("McpTool", { description: "Tool from MCP server", parameters: { type: "object", properties: { query: { type: "string" } }, required: ["query"] }})Signature
declare const dynamic: < const Name extends string, const Options extends { readonly description?: string | undefined readonly parameters?: Schema.Constraint | JsonSchema.JsonSchema | undefined readonly success?: Schema.Constraint | undefined readonly failure?: Schema.Constraint | undefined readonly failureMode?: FailureMode | undefined readonly needsApproval?: NeedsApproval<any> | undefined }>( name: Name, options?: Options) => Dynamic< Name, { 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 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" }>Since v4.0.0
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/unstable/ai"
// Simple tool with no parametersconst GetCurrentTime = Tool.make("GetCurrentTime", { description: "Returns the current timestamp", success: Schema.Number})Signature
declare const make: < const Name extends string, Parameters extends Schema.Constraint = EmptyParams, Success extends Schema.Constraint = Schema.Void, Failure extends Schema.Constraint = Schema.Never, Mode extends FailureMode | undefined = undefined, Dependencies extends Array<Context.Key<any, any> | Context.Key<never, any>> = []>( name: Name, options?: { readonly description?: string | undefined readonly parameters?: Parameters | undefined readonly success?: Success | undefined readonly failure?: Failure | undefined readonly failureMode?: Mode readonly dependencies?: Dependencies | undefined readonly needsApproval?: NeedsApproval<Parameters> | undefined }) => Tool< Name, { readonly parameters: Parameters readonly success: Success readonly failure: Failure readonly failureMode: Mode extends undefined ? "error" : Mode }, Context.Service.Identifier<Dependencies[number]>>Since v4.0.0
providerDefined
Section titled “providerDefined”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.
Example (Creating a provider-defined tool)
import { Schema } from "effect"import { Tool } from "effect/unstable/ai"
// Web search tool provided by OpenAIconst WebSearch = Tool.providerDefined({ id: "openai.web_search", customName: "OpenAiWebSearch", providerName: "web_search", args: Schema.Struct({ query: Schema.String }), success: Schema.Struct({ results: Schema.Array( Schema.Struct({ title: Schema.String, url: Schema.String, content: Schema.String }) ) })})Signature
declare const providerDefined: < const Identifier extends `${string}.${string}`, const Name extends string, Args extends Schema.Constraint = Schema.Void, Parameters extends Schema.Constraint = Schema.Void, Success extends Schema.Constraint = Schema.Void, Failure extends Schema.Constraint = Schema.Never, RequiresHandler extends boolean = false>(options: { readonly id: Identifier readonly customName: Name readonly providerName: string readonly args?: Args | undefined readonly requiresHandler?: RequiresHandler | undefined readonly parameters?: Parameters | undefined readonly success?: Success | undefined readonly failure?: Failure | undefined}) => <Mode extends FailureMode | undefined = undefined>( args: RequiresHandler extends true ? Struct.Simplify<Args["Encoded"] & { readonly failureMode?: Mode | undefined }> : Struct.Simplify<Args["Encoded"]>) => ProviderDefined< Identifier, Name, { readonly args: Args readonly parameters: Parameters readonly success: Success readonly failure: Failure readonly failureMode: Mode extends undefined ? "error" : Mode }, RequiresHandler>Since v4.0.0
converting
Section titled “converting”getJsonSchemaFromSchema
Section titled “getJsonSchemaFromSchema”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 const getJsonSchemaFromSchema: <S extends Schema.Constraint>( schema: S, options?: { readonly transformer?: CodecTransformer }) => JsonSchema.JsonSchemaSince v4.0.0
getters
Section titled “getters”getDescription
Section titled “getDescription”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.
Example (Reading a tool description)
import { Tool } from "effect/unstable/ai"
const myTool = Tool.make("example", { description: "This is an example tool"})
const description = Tool.getDescription(myTool)console.log(description) // "This is an example tool"Signature
declare const getDescription: <Tool extends Any>(tool: Tool) => string | undefinedSince v4.0.0
getJsonSchema
Section titled “getJsonSchema”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.
Example (Generating a tool JSON schema)
import { Schema } from "effect"import { Tool } from "effect/unstable/ai"
const weatherTool = Tool.make("get_weather", { parameters: Schema.Struct({ location: Schema.String, units: Schema.Literals(["celsius", "fahrenheit"]) })})
const jsonSchema = Tool.getJsonSchema(weatherTool)console.log(jsonSchema)// {// type: "object",// properties: {// location: { type: "string" },// units: { type: "string", enum: ["celsius", "fahrenheit"] }// },// required: ["location", "units"]// }Signature
declare const getJsonSchema: <Tool extends Any>( tool: Tool, options?: { readonly transformer?: CodecTransformer }) => JsonSchema.JsonSchemaSince v4.0.0
getStrictMode
Section titled “getStrictMode”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
Strictfor the annotation read by this helper
Signature
declare const getStrictMode: <T extends Any>(tool: T) => boolean | undefinedSince v4.0.0
guards
Section titled “guards”isDynamic
Section titled “isDynamic”Type guard to check if a value is a dynamic tool.
Example (Checking for dynamic tools)
import { Schema } from "effect"import { Tool } from "effect/unstable/ai"
const DynamicTool = Tool.dynamic("DynamicTool", { parameters: { type: "object", properties: {} }})
const UserDefinedTool = Tool.make("Calculator", { parameters: Schema.Struct({ a: Schema.Number, b: Schema.Number }), success: Schema.Number})
console.log(Tool.isDynamic(DynamicTool)) // trueconsole.log(Tool.isDynamic(UserDefinedTool)) // falseSignature
declare const isDynamic: (u: unknown) => u is Dynamic<string, any>Since v4.0.0
isProviderDefined
Section titled “isProviderDefined”Type guard to check if a value is a provider-defined tool.
Example (Checking for provider-defined tools)
import { Schema } from "effect"import { Tool } from "effect/unstable/ai"
const UserDefinedTool = Tool.make("Calculator", { description: "Performs basic arithmetic operations", parameters: Schema.Struct({ operation: Schema.Literals(["add", "subtract", "multiply", "divide"]), a: Schema.Number, b: Schema.Number }), success: Schema.Number})
const ProviderDefinedTool = Tool.providerDefined({ id: "openai.web_search", customName: "OpenAiWebSearch", providerName: "web_search", args: Schema.Struct({ query: Schema.String }), success: Schema.Struct({ results: Schema.Array( Schema.Struct({ title: Schema.String, url: Schema.String, snippet: Schema.String }) ) })})
console.log(Tool.isProviderDefined(UserDefinedTool)) // falseconsole.log(Tool.isProviderDefined(ProviderDefinedTool)) // trueSignature
declare const isProviderDefined: (u: unknown) => u is ProviderDefined<`${string}.${string}`, string, any>Since v4.0.0
isUserDefined
Section titled “isUserDefined”Type guard to check if a value is a user-defined tool.
Example (Checking for user-defined tools)
import { Schema } from "effect"import { Tool } from "effect/unstable/ai"
const UserDefinedTool = Tool.make("Calculator", { description: "Performs basic arithmetic operations", parameters: Schema.Struct({ operation: Schema.Literals(["add", "subtract", "multiply", "divide"]), a: Schema.Number, b: Schema.Number }), success: Schema.Number})
const ProviderDefinedTool = Tool.providerDefined({ id: "openai.web_search", customName: "OpenAiWebSearch", providerName: "web_search", args: Schema.Struct({ query: Schema.String }), success: Schema.Struct({ results: Schema.Array( Schema.Struct({ title: Schema.String, url: Schema.String, snippet: Schema.String }) ) })})
console.log(Tool.isUserDefined(UserDefinedTool)) // trueconsole.log(Tool.isUserDefined(ProviderDefinedTool)) // falseSignature
declare const isUserDefined: (u: unknown) => u is Tool<string, any, any>Since v4.0.0
models
Section titled “models”Dynamic (interface)
Section titled “Dynamic (interface)”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.
Example (Defining dynamic tools)
import { Schema } from "effect"import { Tool } from "effect/unstable/ai"
// Dynamic tool with Effect Schema (typed)const Calculator = Tool.dynamic("Calculator", { parameters: Schema.Struct({ operation: Schema.Literals(["add", "subtract"]), a: Schema.Number, b: Schema.Number }), success: Schema.Number})
// Dynamic tool with JSON Schema (untyped parameters)const McpTool = Tool.dynamic("McpTool", { description: "Tool from MCP server", parameters: { type: "object", properties: { query: { type: "string" } }, required: ["query"] }})Signature
export interface Dynamic< out Name extends string, out Config extends { readonly parameters: Schema.Constraint | JsonSchema.JsonSchema readonly success: Schema.Constraint readonly failure: Schema.Constraint readonly failureMode: FailureMode }, out Requirements = never> extends Tool< Name, { readonly parameters: Config["parameters"] extends Schema.Constraint ? Config["parameters"] : typeof Schema.Unknown readonly success: Config["success"] readonly failure: Config["failure"] readonly failureMode: Config["failureMode"] }, Requirements> { readonly [DynamicTypeId]: typeof DynamicTypeId
/** * The raw JSON Schema for parameters. Present when `parameters` was provided * as a JSON Schema, `undefined` when an Effect Schema was used. */ readonly jsonSchema: Config["parameters"] extends Schema.Constraint ? undefined : JsonSchema.JsonSchema}Since v4.0.0
FailureMode (type alias)
Section titled “FailureMode (type alias)”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"Since v4.0.0
Handler (interface)
Section titled “Handler (interface)”Represents an Tool that has been implemented within the application.
Signature
export interface Handler<Name extends string> { readonly _: unique symbol readonly name: Name readonly context: Context.Context<never> readonly handler: (params: any, ctx: any) => Effect.Effect<any, any>}Since v4.0.0
HandlerOutput (type alias)
Section titled “HandlerOutput (type alias)”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 progressFinal: The last result, which is the authoritative output
Signature
type HandlerOutput<Success> = | { readonly _tag: "Preliminary"; readonly value: Success } | { readonly _tag: "Final"; readonly value: Success }Since v4.0.0
HandlerResult (interface)
Section titled “HandlerResult (interface)”Represents the result of calling the handler for a particular Tool.
Signature
export interface HandlerResult<Tool extends Any> { /** * The result of executing the handler for a particular tool. */ readonly result: Result<Tool> /** * The pre-encoded tool call result of executing the handler for a particular * tool as a JSON-serializable value. The encoded result can be incorporated * into subsequent requests to the large language model. */ readonly encodedResult: unknown /** * Whether the result of executing the tool call handler was an error or not. */ readonly isFailure: boolean /** * Whether this is a preliminary (intermediate) result or the final result. * Preliminary results represent progress updates; only the final result * should be used as the authoritative output. */ readonly preliminary: boolean}Since v4.0.0
NameMapper (class)
Section titled “NameMapper (class)”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> { constructor(tools: Tools)}Since v4.0.0
getCustomName (method)
Section titled “getCustomName (method)”Returns the user-specified tool name that corresponds with the provided provider-specified tool name.
Details
If the provider-specified tool name was not registered with the name mapper, then the provider-specified tool name is returned.
Signature
declare const getCustomName: (providerName: string) => stringgetProviderName (method)
Section titled “getProviderName (method)”Returns the provider-specified tool name that corresponds with the provided user-specified tool name.
Details
If the user-specified tool name was not registered with the name mapper, then the user-specified tool name is returned.
Signature
declare const getProviderName: (customName: string) => string#customToProvider (property)
Section titled “#customToProvider (property)”Signature
readonly #customToProvider: Map<string, string>#providerToCustom (property)
Section titled “#providerToCustom (property)”Signature
readonly #providerToCustom: Map<string, string>NeedsApproval (type alias)
Section titled “NeedsApproval (type alias)”Specifies whether user approval is required before executing a tool.
Details
Can be:
boolean: Static approval requirementNeedsApprovalFunction: Dynamic approval based on parameters/context
Signature
type NeedsApproval<Params> = boolean | NeedsApprovalFunction<Params>Since v4.0.0
NeedsApprovalContext (interface)
Section titled “NeedsApprovalContext (interface)”Context provided to the needsApproval function when dynamically
determining if a tool requires user approval.
Signature
export interface NeedsApprovalContext { /** * The unique identifier of the tool call. */ readonly toolCallId: string /** * The conversation messages leading up to this tool call. */ readonly messages: ReadonlyArray<Prompt.Message>}Since v4.0.0
NeedsApprovalFunction (type alias)
Section titled “NeedsApprovalFunction (type alias)”Function type for dynamically determining if a tool requires approval.
Signature
type NeedsApprovalFunction<Params> = ( params: Params["Type"], context: NeedsApprovalContext) => boolean | Effect.Effect<boolean>Since v4.0.0
ProviderDefined (interface)
Section titled “ProviderDefined (interface)”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.
Example (Defining a provider-defined web search tool)
import { Schema } from "effect"import { Tool } from "effect/unstable/ai"
// Define a web search tool provided by OpenAIconst WebSearch = Tool.providerDefined({ id: "openai.web_search", customName: "OpenAiWebSearch", providerName: "web_search", args: Schema.Struct({ query: Schema.String }), success: Schema.Struct({ results: Schema.Array( Schema.Struct({ title: Schema.String, url: Schema.String, snippet: Schema.String }) ) })})Signature
export interface ProviderDefined< out Identifier extends `${string}.${string}`, out Name extends string, out Config extends { readonly args: Schema.Constraint readonly parameters: Schema.Constraint readonly success: Schema.Constraint readonly failure: Schema.Constraint readonly failureMode: FailureMode }, out RequiresHandler extends boolean = false> extends Tool< Name, { readonly parameters: Config["parameters"] readonly success: Config["success"] readonly failure: Config["failure"] readonly failureMode: Config["failureMode"] }> { readonly [ProviderDefinedTypeId]: typeof ProviderDefinedTypeId
/** * the identifier which is used to uniquely identify the provider-defined tool. */ readonly id: Identifier
/** * The arguments passed to the provider-defined tool. */ readonly args: Config["args"]["Encoded"]
/** * A `Schema` representing the arguments provided by the end-user which will * be used to configure the behavior of the provider-defined tool. */ readonly argsSchema: Config["args"]
/** * Name of the tool as recognized by the large language model provider. */ readonly providerName: string
/** * If set to `true`, this provider-defined tool will require a user-defined * tool call handler to be provided when converting the `Toolkit` containing * this tool into a `Layer`. */ readonly requiresHandler: RequiresHandler}Since v4.0.0
Tool (interface)
Section titled “Tool (interface)”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.
Example (Defining a weather lookup tool)
import { Schema } from "effect"import { Tool } from "effect/unstable/ai"
// Create a weather lookup toolconst GetWeather = Tool.make("GetWeather", { description: "Get current weather for a location", parameters: Schema.Struct({ location: Schema.String, units: Schema.Literals(["celsius", "fahrenheit"]) }), success: Schema.Struct({ temperature: Schema.Number, condition: Schema.String, humidity: Schema.Number })})Signature
export interface Tool< out Name extends string, out Config extends { readonly parameters: Schema.Constraint readonly success: Schema.Constraint readonly failure: Schema.Constraint readonly failureMode: FailureMode }, out Requirements = never> { readonly [TypeId]: { readonly _Requirements: Types.Covariant<Requirements> }
/** * The tool identifier which is used to uniquely identify the tool. */ readonly id: string
/** * The name of the tool. */ readonly name: Name
/** * The optional description of the tool. */ readonly description?: string | undefined
/** * 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. */ readonly failureMode: FailureMode
/** * A `Schema` representing the parameters that a tool must be called with. */ readonly parametersSchema: Config["parameters"]
/** * A `Schema` representing the value that a tool must return when called if * the tool call is successful. */ readonly successSchema: Config["success"]
/** * A `Schema` representing the value that a tool must return when called if * it fails. */ readonly failureSchema: Config["failure"]
/** * A `Context` containing tool annotations which can store metadata about * the tool. */ readonly annotations: Context.Context<never>
/** * Specifies whether user approval is required before executing this tool. * * **Details** * * - If `undefined` or `false`, the tool executes immediately. * - If `true`, the tool always requires approval. * - If a function, it is called with the tool parameters and context to * dynamically determine if approval is needed. The function can return * a boolean or an Effect that resolves to a boolean. */ readonly needsApproval?: boolean | NeedsApprovalFunction<any> | undefined
/** * Adds a _request-level_ dependency which must be provided before the tool * call handler can be executed. * * **Details** * * This can be useful when you want to enforce that a particular dependency * **MUST** be provided to each request to the large language model provider * instead of being provided when creating the tool call handler layer. */ addDependency<Identifier, Service>( tag: Context.Key<Identifier, Service> ): Tool<Name, Config, Identifier | Requirements>
/** * Set the schema to use to validate the result of a tool call when successful. */ setSuccess<SuccessSchema extends Schema.Constraint>( schema: SuccessSchema ): Tool< Name, { readonly parameters: Config["parameters"] readonly success: SuccessSchema readonly failure: Config["failure"] readonly failureMode: Config["failureMode"] }, Requirements >
/** * Set the schema to use to validate the result of a tool call when it fails. */ setFailure<FailureSchema extends Schema.Constraint>( schema: FailureSchema ): Tool< Name, { readonly parameters: Config["parameters"] readonly success: Config["success"] readonly failure: FailureSchema readonly failureMode: Config["failureMode"] }, Requirements >
/** * Set the schema to use to validate the parameters of a tool call. */ setParameters<ParametersSchema extends Schema.Constraint>( schema: ParametersSchema ): Tool< Name, { readonly parameters: ParametersSchema readonly success: Config["success"] readonly failure: Config["failure"] readonly failureMode: Config["failureMode"] }, Requirements >
/** * Add an annotation to the tool. */ annotate<I, S>(tag: Context.Key<I, S>, value: S): Tool<Name, Config, Requirements>
/** * Add many annotations to the tool. */ annotateMerge<I>(context: Context.Context<I>): Tool<Name, Config, Requirements>}Since v4.0.0
schemas
Section titled “schemas”EmptyParams
Section titled “EmptyParams”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
makefor the tool constructor that defaults omitted parameters to this schema
Signature
declare const EmptyParams: EmptyParamsSince v4.0.0
EmptyParams (interface)
Section titled “EmptyParams (interface)”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
export interface EmptyParams extends Schema.$Record<Schema.String, Schema.Never> {}Since v4.0.0
type IDs
Section titled “type IDs”DynamicTypeId
Section titled “DynamicTypeId”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: "~effect/ai/Tool/Dynamic"Since v4.0.0
DynamicTypeId (type alias)
Section titled “DynamicTypeId (type alias)”Type-level representation of the dynamic tool runtime type identifier.
Signature
type DynamicTypeId = "~effect/ai/Tool/Dynamic"Since v4.0.0
ProviderDefinedTypeId
Section titled “ProviderDefinedTypeId”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: "~effect/ai/Tool/ProviderDefined"Since v4.0.0
ProviderDefinedTypeId (type alias)
Section titled “ProviderDefinedTypeId (type alias)”Type-level representation of the provider-defined tool runtime type identifier.
Signature
type ProviderDefinedTypeId = "~effect/ai/Tool/ProviderDefined"Since v4.0.0
TypeId
Section titled “TypeId”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: "~effect/ai/Tool"Since v4.0.0
TypeId (type alias)
Section titled “TypeId (type alias)”Type-level representation of the Effect AI tool runtime type identifier.
Signature
type TypeId = "~effect/ai/Tool"Since v4.0.0
unsafe
Section titled “unsafe”unsafeSecureJsonParse
Section titled “unsafeSecureJsonParse”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 const unsafeSecureJsonParse: (text: string) => unknownSince v4.0.0
utility types
Section titled “utility types”Any (interface)
Section titled “Any (interface)”A type which represents any Tool.
Signature
export interface Any extends Tool< any, { readonly parameters: Schema.Top readonly success: Schema.Top readonly failure: Schema.Top readonly failureMode: FailureMode }, any> {}Since v4.0.0
AnyDynamic (interface)
Section titled “AnyDynamic (interface)”A type which represents any dynamic Tool.
Signature
export interface AnyDynamic extends Dynamic< any, { readonly parameters: Schema.Top | JsonSchema.JsonSchema readonly success: Schema.Top readonly failure: Schema.Top readonly failureMode: FailureMode }, any> {}Since v4.0.0
AnyProviderDefined (interface)
Section titled “AnyProviderDefined (interface)”A type which represents any provider-defined Tool.
Signature
export interface AnyProviderDefined extends ProviderDefined< any, any, { readonly args: Schema.Top readonly parameters: Schema.Top readonly success: Schema.Top readonly failure: Schema.Top readonly failureMode: FailureMode }, any> {}Since v4.0.0
Failure (type alias)
Section titled “Failure (type alias)”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"] : neverSince v4.0.0
FailureEncoded (type alias)
Section titled “FailureEncoded (type alias)”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"] : neverSince v4.0.0
FailureResult (type alias)
Section titled “FailureResult (type alias)”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"] : neverSince v4.0.0
FailureResultEncoded (type alias)
Section titled “FailureResultEncoded (type alias)”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"] : neverSince v4.0.0
HandlerError (type alias)
Section titled “HandlerError (type alias)”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 : neverSince v4.0.0
HandlerServices (type alias)
Section titled “HandlerServices (type alias)”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> // Parameters must be decoded when received from a model ? | _Config["parameters"]["DecodingServices"] // A tool call `result`, whether success or failure, is encoded and returned // as the `encodedResult` along with the `result` | ResultEncodingServices<T> // Per-request requirements | _Requirements : neverSince v4.0.0
HandlersFor (type alias)
Section titled “HandlersFor (type alias)”A utility type to create a union of Handler types for all tools in a
record.
Signature
type HandlersFor<Tools> = { [Name in keyof Tools]: RequiresHandler<Tools[Name]> extends true ? Handler<Tools[Name]["name"]> : never}[keyof Tools]Since v4.0.0
Name (type alias)
Section titled “Name (type alias)”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 : neverSince v4.0.0
Parameters (type alias)
Section titled “Parameters (type alias)”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"] : neverSince v4.0.0
ParametersEncoded (type alias)
Section titled “ParametersEncoded (type alias)”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"] : neverSince v4.0.0
ParametersSchema (type alias)
Section titled “ParametersSchema (type alias)”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"] : neverSince v4.0.0
RequiresHandler (type alias)
Section titled “RequiresHandler (type alias)”A utility type to determine if the specified tool requires a user-defined handler to be implemented.
Signature
type RequiresHandler<Tool> = Tool extends ProviderDefined<infer _Name, infer _Config, infer _RequiresHandler> ? _RequiresHandler : trueSince v4.0.0
Result (type alias)
Section titled “Result (type alias)”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> : neverSince v4.0.0
ResultDecodingServices (type alias)
Section titled “ResultDecodingServices (type alias)”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"] : neverSince v4.0.0
ResultEncoded (type alias)
Section titled “ResultEncoded (type alias)”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> : neverSince v4.0.0
ResultEncodingServices (type alias)
Section titled “ResultEncodingServices (type alias)”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"] : neverSince v4.0.0
Success (type alias)
Section titled “Success (type alias)”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"] : neverSince v4.0.0
SuccessEncoded (type alias)
Section titled “SuccessEncoded (type alias)”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"] : neverSince v4.0.0
SuccessSchema (type alias)
Section titled “SuccessSchema (type alias)”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"] : neverSince v4.0.0