Skip to content

Documentation navigation

Decorators

Dependency decorators for tools, agents, data, and interrupts.

#Decorators

Decorators declare how tools relate to each other, to agents, and to data that never reaches the model. The SDK sends this metadata with each invocation, and the planner uses it to order calls and fill arguments.

depends_on_decision lives with the decision API; see Decisions.

#Import

Python
from maivn import (
    depends_on_tool,
    depends_on_agent,
    depends_on_private_data,
    depends_on_interrupt,
    depends_on_await_for,
    depends_on_reevaluate,
    requires_producer_reference,
    compose_argument_policy,
    tool_output,
    # Toolset class pattern
    toolify,
    toolset,
    toolify_options,
    toolset_options,
    # Permission helpers used with @toolify(permissions=...)
    PermissionFlag,
    PermissionSet,
    PERMISSION_FLAG_NAMES,
    require_permissions,
    # Provider metadata for toolset classes
    AuthMode,
    ProviderCapability,
    ProviderMetadata,
)

#requires_producer_reference

Declares that one argument path accepts only a reference produced by a named upstream tool. Generator toolsets use this metadata to expose their dependency graph to the planner while enforcing the same requirement when the tool runs.

Plain text
def requires_producer_reference(
    argument_path: str,
    *,
    producer_tool_name: str,
    reference_kind: Literal['composition_reference'] = 'composition_reference',
) -> Callable
ParameterTypeDefaultDescription
argument_pathstrRequiredDotted path to the argument, such as block.content. Each segment must be a Python identifier.
producer_tool_namestrRequiredName of the tool that issues the reference. Letters, digits, _ and -, starting with a letter or _. Keyword-only.
reference_kind'composition_reference''composition_reference'The only supported kind. Keyword-only.

An invalid path or tool name raises ValueError, as does declaring the same argument_path twice on one function.

Python
@requires_producer_reference(
    'block.content',
    producer_tool_name='DOCUMENTS_compose_artifact',
)
@agent.toolify(description='Insert a composed document block')
def put_block(block: dict) -> dict:
    ...

This metadata does not inject a whole prior result. The receiving tool must still validate that the nominal reference exists and belongs to its own workspace.

#compose_argument_policy

Controls whether the compose_argument system tool may write one argument of a tool. compose_argument asks a stronger model to draft a large argument, such as a document body, and hands the receiving tool a reference to the result. It only runs when you allow it; see System tools.

Plain text
def compose_argument_policy(
    arg_name: str,
    *,
    mode: Literal['allow', 'require', 'forbid'] = 'allow',
    approval: Literal['none', 'explicit'] = 'none',
) -> Callable
ParameterTypeDefaultDescription
arg_namestrRequiredA top-level parameter of the decorated function. Dotted paths are rejected.
mode'allow' | 'require' | 'forbid''allow''forbid' makes the platform refuse composition for this argument with compose_argument_forbidden. 'require' also records a producer requirement for compose_argument on the argument, as requires_producer_reference would. Keyword-only.
approval'none' | 'explicit''none'With 'explicit', composition is refused with compose_argument_approval_required unless the target appears in SystemToolsConfig.approved_compose_argument_targets. Keyword-only.
Python
from maivn import Agent, SystemToolsConfig, compose_argument_policy

agent = Agent(name='mailer', api_key='...')


@agent.toolify(description='Send a drafted email')
@compose_argument_policy('body', mode='require', approval='explicit')
def send_email(to: str, body: str) -> dict:
    return {'sent_to': to}


response = agent.invoke(
    'Email the team a summary of the launch plan.',
    system_tools_config=SystemToolsConfig(
        allowed_tools=['compose_argument'],
        approved_compose_argument_targets=['send_email.body'],
    ),
)

Entries in approved_compose_argument_targets are tool.argument strings. The platform also accepts tool.* for every argument of one tool and * for all targets. The decorator raises ValueError when arg_name is not a parameter of the function, when it contains a dot, when mode or approval is not one of the listed values, or when you declare a second policy for the same argument.

#tool_output

Declare the output schema for a function or method tool when the Python return type is too generic to describe the public result contract.

Plain text
def tool_output(
    schema: type[BaseModel] | dict[str, object],
) -> Callable

#Parameters

ParameterTypeDescription
schematype[BaseModel] | dict[str, object]Pydantic model class or JSON Schema object describing the tool result

#Example

Python
from pydantic import BaseModel

from maivn import Agent, tool_output


class SearchMessagesResult(BaseModel):
    message_ids: list[str]
    next_page_token: str | None = None


agent = Agent(name='mail', api_key='...')


@tool_output(SearchMessagesResult)
def search_messages(query: str) -> dict[str, object]:
    """Search recent messages."""
    return {'message_ids': ['m-1'], 'next_page_token': None}


agent.add_tool(search_messages)

@tool_output(...) is not a registration marker. It works with direct agent.add_tool(fn) registration, and with toolset methods that are already discovered through @toolify or @toolset(require_marker=False). It does not expose an otherwise unmarked toolset method.

For app-specific result handling, declare @tool_output on a wrapper function. Current add_tool and add_toolset methods do not accept override arguments.

#depends_on_tool

Declare a dependency on another tool's output.

Plain text
def depends_on_tool(
    tool_ref: str | Callable | type,
    arg_name: str,
    *,
    revision_policy: Literal['on_validation_error'] | None = None,
    result_scope: Literal['invocation', 'conversation'] = 'invocation',
) -> Callable

#Parameters

ParameterTypeDescription
tool_refstr | Callable | typeThe producer: its registered name, the decorated function, or a Pydantic model class
arg_namestrFunction argument to receive the tool's output
revision_policyLiteral['on_validation_error'] | NoneExplicitly allow reconstruction after a dependent validation failure; the default does not
result_scopeLiteral['invocation', 'conversation']Allow a result only in the current invocation (default), or opt this edge into trusted reuse in the same conversation. Any other value raises ValueError.

#Example

Python
from maivn import Agent, depends_on_tool

agent = Agent(name='data_agent', api_key='...')

@agent.toolify(description='Fetch raw data')
def fetch_data(source: str) -> dict:
    return {'source': source, 'records': [...]}

@agent.toolify(description='Process fetched data')
@depends_on_tool(fetch_data, arg_name='raw_data')
def process_data(raw_data: dict) -> dict:
    # 'raw_data' is automatically populated with fetch_data's output
    return {'processed': len(raw_data['records'])}

result_scope='invocation' is the safe default. The producer must complete in the current invocation before the consumer can run. Use result_scope='conversation' only for a stable result that may remain valid on a later turn in the same thread:

Python
@agent.toolify(description='Load the customer profile')
def load_customer_profile(customer_id: str) -> dict:
    return {'customer_id': customer_id, 'service_tier': 'enterprise'}

@agent.toolify(description='Draft a reply using the customer profile')
@depends_on_tool(
    load_customer_profile,
    arg_name='profile',
    result_scope='conversation',
)
def draft_reply(profile: dict) -> dict:
    return {'reply': f'Reply for {profile["customer_id"]}'}

Conversation scope is permission on this dependency edge, rather than a request to restore the whole graph. Reuse requires the same thread and matching producer spec, and the platform supplies only a trusted, successfully stored result. If the producer runs again, that fresh attempt is authoritative: its result wins, and a failed refresh does not fall back to an older success. Keep confirmations, authorization checks and anything that goes stale at invocation scope.

The fluent form agent.toolify(...).depends_on_tool(...) accepts revision_policy and result_scope, the same as the decorator.

#Chaining multiple dependencies

Python
@agent.toolify(description='Step 1')
def step_one() -> dict:
    return {'step': 1}

@agent.toolify(description='Step 2')
def step_two() -> dict:
    return {'step': 2}

@agent.toolify(description='Final step')
@depends_on_tool(step_one, arg_name='result_one')
@depends_on_tool(step_two, arg_name='result_two')
def final_step(result_one: dict, result_two: dict) -> dict:
    return {'combined': [result_one, result_two]}

#depends_on_agent

Declare a dependency on another agent's output.

Plain text
def depends_on_agent(
    agent_ref: str | Agent,
    arg_name: str,
) -> Callable

#Parameters

ParameterTypeDescription
agent_refstr | AgentAgent reference (Agent object, agent ID, or name)
arg_namestrFunction argument to receive the agent's output

#Example

Python
from maivn import Agent, Swarm, depends_on_agent

researcher = Agent(name='researcher', api_key='...')
writer = Agent(name='writer', api_key='...')

@researcher.toolify(description='Research a topic')
def research(topic: str) -> dict:
    return {'findings': f'Research on {topic}'}

@writer.toolify(description='Write based on research')
@depends_on_agent(researcher, arg_name='research_result')
def write_article(research_result: dict) -> dict:
    return {'article': f'Article based on: {research_result}'}

swarm = Swarm(name='team', agents=[researcher, writer])

#How it works

Both agents must be members of the same Swarm, and the swarm is what you invoke. When a tool depends on an agent:

  1. The swarm identifies the dependency
  2. The dependent agent is invoked first, with the user's request
  3. Its output is passed to the tool's specified argument

For one member waiting on another, prefer swarm.member.depends_on_agent(...) (see Member registration with dependencies).

#depends_on_private_data

Inject a private value into a tool at execution time.

Plain text
def depends_on_private_data(
    data_key: str,
    arg_name: str,
) -> Callable

#Parameters

ParameterTypeDescription
data_keystrKey in the agent's private_data dictionary
arg_namestrFunction argument to receive the value

#Example

Python
from maivn import Agent, depends_on_private_data

agent = Agent(name='api_agent', api_key='...')

@agent.toolify(description='Call external API')
@depends_on_private_data(data_key='api_secret', arg_name='secret')
def call_external_api(query: str, secret: str) -> dict:
    # 'secret' is injected at runtime, never exposed to LLM
    return {'result': f'API response for {query}'}

# Set private data
agent.private_data = {'api_secret': 'sk-xxx-secret-key'}

#Security Model

Private data follows strict security boundaries:

  1. Schema-only planning: LLM sees only field names/types, never values
  2. Runtime injection: Values injected at execution time, held within the runtime
  3. Automatic redaction: Results containing private data are redacted
  4. SDK event boundary: Resolved private values are excluded from SDK listener and frontend-safe event payloads. Your tool code remains responsible for not logging or returning them.

#Pydantic Class Targets

@depends_on_private_data works on @agent.toolify'd Pydantic model classes the same way it works on function tools. The declared field is hidden from the model-facing input schema and populated at SDK validation time:

Python
from maivn import Agent, depends_on_private_data
from pydantic import BaseModel

agent = Agent(name='audit_agent', api_key='...')

@depends_on_private_data(data_key='customer_ssn', arg_name='ssn')
@agent.toolify(name='audit_record', description='Record an audit entry', final_tool=True)
class AuditRecord(BaseModel):
    ssn: str        # injected at execution time from private_data['customer_ssn']
    note: str       # supplied by the LLM

    def __call__(self) -> dict:
        return {'ssn_last4': self.ssn[-4:], 'note': self.note}

The decorator does not validate a missing model field at import time. A bad name can fail later during schema generation or validation. Match the name to an actual field and inspect the compiled tool before serving it.

#depends_on_interrupt

Collect user input during tool execution.

Plain text
def depends_on_interrupt(
    arg_name: str,
    input_handler: Callable[[str], object],
    prompt: str = "",
    input_type: InputType | None = None,
    choices: list[str] | None = None,
) -> Callable

InputType is Literal['text', 'choice', 'boolean', 'number']. It is not exported from maivn.

#Parameters

ParameterTypeDefaultDescription
arg_namestrRequiredFunction argument to receive user input
input_handlerCallable[[str], object]RequiredFunction that collects input. It always receives one positional argument, the prompt. It may be async.
promptstr""Prompt passed to the handler. When empty, the handler receives '<arg_name>: '. Pass AgentGenerated to let the runtime write the question; see Interrupts.
input_typeInputType | NoneNoneOverride the input type. When unset, auto-detected from the parameter's type annotation (e.g., bool -> 'boolean', int/float -> 'number', Literal[...] -> 'choice', otherwise 'text')
choiceslist[str] | NoneNoneOverride choices for 'choice' inputs. When unset, auto-detected from Literal[...] annotations. Choices are appended to the prompt string the handler receives.

The decorated argument is hidden from the model-facing schema. A 'boolean' answer accepts True/False or the strings yes, y, true, 1, no, n, false and 0. A 'number' answer must be a finite number. Anything else raises ValueError.

#Example

Python
from maivn import Agent, depends_on_interrupt, default_terminal_interrupt

agent = Agent(name='interactive', api_key='...')

@agent.toolify(description='Greet the user')
@depends_on_interrupt(
    arg_name='user_name',
    input_handler=default_terminal_interrupt,
    prompt='Please enter your name: ',
)
def greet_user(user_name: str) -> dict:
    return {'greeting': f'Hello, {user_name}!'}

#Custom input handler

A handler is called with one positional argument whether or not you set prompt. When your handler has its own prompting logic, omit prompt and ignore the value:

Python
def file_picker_dialog(_prompt: str) -> str:
    # Custom GUI dialog - the prompt text is not needed
    return show_file_picker()

@agent.toolify()
@depends_on_interrupt(arg_name='file_path', input_handler=file_picker_dialog)
def process_file(file_path: str) -> dict:
    return {'processed': file_path}

With a prompt:

Python
def custom_handler(prompt: str) -> str:
    # Custom logic (GUI dialog, API call, etc.)
    return get_input_from_somewhere(prompt)

@agent.toolify()
@depends_on_interrupt(
    arg_name='choice',
    input_handler=custom_handler,
    prompt='Select an option (1-3): ',
)
def process_choice(choice: str) -> dict:
    return {'selected': choice}

#Interrupt flow

  1. Tool execution reaches the interrupt dependency
  2. Execution pauses
  3. input_handler runs in your process with the prompt
  4. User provides input
  5. The SDK submits the answer and execution resumes with the value

#depends_on_await_for

Declares that a tool must wait for another tool without taking its output.

Enforced since maivn 2.5.0. Earlier releases recorded the declaration but did not send it, so it had no effect. The platform needs a release with await-for support; see What the platform does. To pass the first tool's output to the second, use depends_on_tool instead.
Plain text
def depends_on_await_for(
    tool_ref: str | Callable | type,
    *,
    timing: Literal['before', 'after'] = 'after',
    instance_control: Literal['each', 'first', 'last', 'all'] = 'each',
) -> Callable
timing and instance_control are keyword-only.

#Parameters

ParameterTypeDefaultDescription
tool_refstr | Callable | typeRequiredThe tool this one should wait for, by registered name, function or model class. It must be a tool of the same agent.
timing'before' | 'after''after''after': this tool waits for the referenced tool. 'before': the referenced tool waits for this one.
instance_control'each' | 'first' | 'last' | 'all''each'How many completions of the waited-for tool the wait needs. See the table below.

#Example

Python
from maivn import Agent, depends_on_await_for

agent = Agent(name='workflow_agent', api_key='...')

@agent.toolify(description='Fetch raw data')
def fetch_data(source: str) -> dict:
    return {'source': source}

@agent.toolify(description='Write audit log after fetch completes')
@depends_on_await_for(fetch_data)
def write_audit_entry() -> dict:
    return {'logged': True}

#What the platform does (await-for)

The SDK sends each declaration with the invocation. The platform holds the waiting tool until the tool it waits for has completed successfully in the same run.

  • If the model requests both tools in the same batch, the waiting call runs after the other one.
  • Otherwise the platform refuses the waiting call with the retryable error code tool_await_for_pending. The message names the tool to call first. The call never reaches your code, and the model can call the other tool and then retry.
  • A tool the platform schedules itself waits silently instead of being refused.
  • Two tools that wait for each other cannot deadlock: the platform refuses both rather than holding them.
  • With timing='before', the referenced tool waits for the declaring tool.

instance_control sets how many completions the wait needs:

instance_controlThe waiting call may run when
'each'The nth waiting call has the nth successful completion of the other tool
'first'The other tool has completed successfully once
'last'The most recent requested call of the other tool succeeded
'all'Every requested call of the other tool has finished and at least one succeeded

References are resolved against the tools you registered. A reference by function, method or model class matches the tool's registered name, so a tool registered with a custom name= works. A reference that matches no tool of the declaring agent raises ConfigurationError before anything is sent. So does a reference to another agent's tool: each agent's tools run in their own run, so a control must name a tool of the same agent.

Controls on a delegate agent's tools or a swarm member's tools are sent too, and the platform enforces them in the child run that executes those tools. If decomposing a graph into jobs would put a control's two tools in different runs, the platform runs that graph as one run instead.

Await-for needs a platform release that supports it. An older server answers 422 with a message that it is too old for depends_on_await_for. Deploy the platform first, then upgrade the SDK.

#depends_on_reevaluate

Declares that planning must pause at a boundary around another tool, look at the results so far, and plan again.

Plain text
def depends_on_reevaluate(
    tool_ref: str | Callable | type,
    *,
    timing: Literal['before', 'after'] = 'after',
    instance_control: Literal['each', 'first', 'last', 'all'] = 'each',
) -> Callable
timing and instance_control are keyword-only.

#Parameters

ParameterTypeDefaultDescription
tool_refstr | Callable | typeRequiredThe tool that defines the boundary, by registered name, function or model class
timing'before' | 'after''after'Whether the boundary falls before or after the referenced tool
instance_control'each' | 'first' | 'last' | 'all''each'Which calls of the referenced tool in one turn set the boundary

#Example

Python
from maivn import Agent, depends_on_reevaluate

agent = Agent(name='planning_agent', api_key='...')

@agent.toolify(description='Fetch source material')
def fetch_source() -> dict:
    return {'content': '...'}

@agent.toolify(description='Summarize after reviewing fetched content')
@depends_on_reevaluate(fetch_source, timing='after', instance_control='all')
def summarize_source() -> dict:
    return {'summary': '...'}

#What the platform does

The SDK sends each declaration as a reevaluate_controls entry. When the model requests the referenced tool in a turn, the platform runs only the calls up to the boundary, then re-plans with those results in context. You do not need the model to plan a reevaluate step for a declared boundary.

Where the boundary falls depends on timing and instance_control:

timinginstance_controlBoundary
'before'anyBefore the first call to the referenced tool in the turn
'after''each' or 'first'Right after the first call to the referenced tool in the turn
'after''all' or 'last'After the last call to the referenced tool in the turn

As with depends_on_await_for, references resolve to the tool's registered name, and a reference to no tool of the declaring agent, or to another agent's tool, raises ConfigurationError before anything is sent. Controls on a delegate agent's or swarm member's tools are enforced in the child run that executes them, and a graph whose control would cross a job boundary runs as one run.

Each declared boundary fires once per invocation. The platform emits a raw system_tool_chunk event with stage: "reevaluate" and phase: "reevaluate_accrued" when it does. The payload carries reevaluate_count and a reevaluate object whose controls list the boundaries that fired. See Reevaluate cycles.

#Decorator Order

Decorators can be stacked in any order. The @agent.toolify() decorator should typically be closest to the function:

Python
@depends_on_tool(step_one, 'result_one')
@depends_on_private_data('secret', 'api_key')
@agent.toolify(description='Final processing')
def process(result_one: dict, api_key: str) -> dict:
    return {'processed': True}

Or with @agent.toolify() on top:

Python
@agent.toolify(description='Final processing')
@depends_on_tool(step_one, 'result_one')
@depends_on_private_data('secret', 'api_key')
def process(result_one: dict, api_key: str) -> dict:
    return {'processed': True}

Both orders work correctly.

The same dependency decorators also work before registering tools with Agent(..., tools=[...]) or agent.add_tool(...):

Python
@depends_on_tool(step_one, 'result_one')
def process(result_one: dict) -> dict:
    """Process the first step result."""
    return {'processed': True}

agent = Agent(name='processor', api_key='...', tools=[step_one, process])

For swarm member agents, stack dependency decorators before @swarm.member on a zero-argument agent factory, or use the builder form such as swarm.member.depends_on_agent(...):

Python
@swarm.member
@depends_on_tool(load_context, 'context')
def researcher() -> Agent:
    return Agent(name='researcher', api_key='...')

writer = swarm.member.depends_on_agent(
    researcher,
    arg_name='research_notes',
)(Agent(name='writer', api_key='...'))

#Validation

Dependency decorators record metadata. Do not rely on them to reject every unknown arg_name at import time. Match each argument to a real function parameter or model field; compile the tools and test the dependency path before deployment. compose_argument_policy and requires_producer_reference validate their targets when you apply them.

A tool dependency cycle is not caught when you decorate or when you call compile_tools(). An agent-to-agent cycle raises ValueError ("Agent dependency cycle cannot be serialized") when the SDK builds the request.

#Dependency Resolution

The SDK sends your declarations with the invocation, and the platform plans and orders the calls from them:

  1. Tools with no dependencies can run first, in the same batch
  2. Dependent tools wait for the tools they depend on
  3. The final tool runs last (if force_final_tool=True)

#Parallel execution

Independent dependencies can run in the same batch:

Python
@agent.toolify()
def fetch_a() -> dict: ...

@agent.toolify()
def fetch_b() -> dict: ...

@agent.toolify()
@depends_on_tool(fetch_a, 'a')
@depends_on_tool(fetch_b, 'b')
def combine(a: dict, b: dict) -> dict:
    # fetch_a and fetch_b are independent, so they can run together
    return {'combined': [a, b]}

#Toolset decorators

The dependency decorators above declare data flow between individual tools. The toolset decorators below promote a configured class to a collection of related tools that share an instance (a database handle, an HTTP client, an OAuth token, etc.).

#@toolset

Marks a class as a toolset. Two forms:

Python
from maivn import toolset


@toolset
class Plain:
    ...


@toolset(prefix='github', tags=['developer'], require_marker=True)
class Configured:
    ...
ArgumentDefaultEffect
prefixsnake_case class name (also used when you pass an empty string)Prepended to each method-tool name. The prefix is uppercased and joined with _ (e.g. prefix='gmail' + method get_message → GMAIL_get_message). The uppercase form keeps tool names compliant with the OpenAI/Anthropic tool-name regex ^[a-zA-Z0-9_-]{1,64}$ and makes the namespace boundary readable in logs.
tags()Tags applied to every method-tool produced.
require_markerTrueWhen True, only @toolify-marked methods are tools. Setting False exposes every public method — discouraged for new code. Names starting with _, nested classes, properties, classmethods and staticmethods are never exposed.
metadata{}Free-form metadata merged into every method-tool. A method's own metadata wins on a key clash.

tags and metadata accept any list or tuple and mapping; they are stored as a tuple and a dict.

#@toolify (method form)

When applied inside a @toolset class, @toolify marks an individual method as a tool and declares its metadata. maivn.toolify only records options on the method. It does not register anything: agent.add_toolset(instance) reads the options, and @agent.toolify(...) is the decorator that registers a free function.

Plain text
def toolify(
    func=None,
    *,
    name: str | None = None,
    description: str | None = None,
    permissions: PermissionSet | None = None,
    destructive: bool = False,
    always_execute: bool = False,
    final_tool: bool = False,
    metadata: Mapping[str, object] | None = None,
    tags: list[str] | tuple[str, ...] | None = None,
    before_execute: Callable | None = None,
    after_execute: Callable | None = None,
)

Use it bare (@toolify) or with keyword arguments. Every option is keyword-only.

Plain text
from maivn import PermissionFlag, PermissionSet, toolify


class Example:
    @toolify
    def simple(self) -> None:
        """Bare form. No permission tags, no destructive marker."""

    @toolify(
        name='renamed',                            # override the exposed tool name
        description='...',                         # override the docstring
        permissions=PermissionSet(PermissionFlag.WRITE),
        destructive=False,
        always_execute=False,
        final_tool=False,
        tags=['payments'],
        metadata={'audit_zone': 'high'},
        before_execute=...,
        after_execute=...,
    )
    def write_payment(self, ...): ...

@toolify coexists with the dependency decorators above (@depends_on_tool, @depends_on_agent, @depends_on_reevaluate, etc.). Order does not matter. Each decorator attaches its own attribute and the SDK's dependency collector reads them all at registration time.

Tools that carry destructive=True, or DELETE, IMPORT, ADMIN or IMPERSONATE permission, are refused when the model calls them, unless the tool opts in to approval with approval_policy (new in maivn 2.5.0). See Approval for privileged tools.

#Reading options back

toolify_options and toolset_options return the options the decorators recorded. Use them to build catalogs, audit logs or tests without knowing the attribute names the decorators write to.

Plain text
def toolify_options(method: Callable) -> MethodToolifyOptions | None
def toolset_options(cls: type) -> ToolsetOptions | None

Both return None when the target was not decorated. MethodToolifyOptions has the fields name, description, permissions, destructive, always_execute, final_tool, metadata, tags (a tuple), before_execute and after_execute. ToolsetOptions has prefix, tags (a tuple), require_marker and metadata.

Python
from maivn import PermissionFlag, PermissionSet, toolify, toolify_options, toolset, toolset_options


@toolset(prefix='reports', tags=['analytics'])
class Reports:
    @toolify(permissions=PermissionSet(PermissionFlag.READ))
    def weekly_signups(self, week_of: str) -> list[dict]:
        """Signup counts for the week starting week_of."""
        return []


print(toolset_options(Reports).prefix)                      # reports
print(toolify_options(Reports.weekly_signups).permissions)  # PermissionSet(['read'])
print(toolify_options(Reports.weekly_signups).tags)         # ()

#Permission helpers

PermissionFlag is a Flag enum; PermissionSet is an immutable bitfield wrapper. The SDK auto-derives tag names from the declared permissions (READ → "read", DELETE → "delete" + "destructive", etc.) so filters like include_tags=["read"] and exclude_tags=["destructive"] work without you having to add those strings to each method's tags= list.

FlagAuto-tags added
READ"read"
WRITE"write"
DELETE"delete", "destructive"
EXPORT"export"
IMPORT"import", "destructive"
ADMIN"admin", "destructive"
IMPERSONATE"impersonate", "destructive"

Setting destructive=True on @toolify(...) also adds "destructive" regardless of the permission flags.

PERMISSION_FLAG_NAMES maps each flag to its lowercase name, in declaration order. PermissionFlag.NONE has no name.

PermissionSet is built from a flag (PermissionSet(PermissionFlag.READ | PermissionFlag.WRITE)) or from names (PermissionSet.from_names(['read', 'write']), which raises ValueError for an unknown name). PermissionSet.all() holds every flag. Instances support includes(flag), flag in permission_set, is_empty(), is_destructive(),

to_list(), flags, and | and & with another set or flag.

Hosts can validate a caller's grant against a tool's declared set with require_permissions(granted, required). required may be a PermissionSet or a single PermissionFlag. It raises PermissionError if any flag in required is missing from granted.

#ProviderMetadata

Attach a ProviderMetadata instance as a class attribute named metadata to advertise provider identity, supported auth modes, scopes (a name-to-description mapping) and capabilities. The runtime treats the attribute as descriptive only and never inspects it for behavior, but hosts can surface it in catalogs or audit logs.

Python
from maivn import AuthMode, ProviderCapability, ProviderMetadata, toolset


@toolset(prefix='reports')
class WeeklyReportsToolSet:
    metadata = ProviderMetadata(
        name='weekly_reports',
        display_name='Weekly KPI Reports',
        version='1.0.0',
        description='Pull weekly KPI reports from an internal warehouse.',
        auth_modes=(AuthMode.NONE,),
        capabilities=frozenset({ProviderCapability.READ}),
        tags=('analytics',),
    )
    ...

#Registration

Python
agent.add_toolset(instance)
agent.add_toolset(other_instance)   # multiple toolsets accumulate

add_toolset walks the class, finds every @toolify-marked method, and creates one ToolMetadata entry per method bound to the instance. Tools are appended to agent.tools so anything that inspects the agent's tool list sees them the same way it sees free callables. It returns the list of entries it registered, and Swarm has the same method.

It raises TypeError when the instance's class is not decorated with @toolset, and ValueError when two methods produce the same prefixed name.

#Filter kwargs
Plain text
agent.add_toolset(instance, *,
    include=None,        # list[str]: only these method names register
    exclude=None,        # list[str]: skip these method names
    include_tags=None,   # list[str]: only methods with any matching tag
    exclude_tags=None,   # list[str]: skip methods with any matching tag
)

Filters compose: a method must pass every active filter. include / exclude match the unprefixed method name (or the name= override on @toolify). Tag matching uses the union of the toolset's tags, the method's tags, and the auto-derived permission tags described above.

If filters drop every method and the toolset has require_marker=True (the default), add_toolset raises ValueError.

#App-specific changes

Current add_toolset does not accept overrides= and add_tool does not accept override=. Use the supported registration arguments or an application wrapper.

#See Also