### Install agentmail-toolkit via npm Source: https://github.com/agentmail-to/agentmail-toolkit/blob/main/node/README.md Install the AgentMail Toolkit package using npm. ```sh npm install agentmail-toolkit ``` -------------------------------- ### Basic usage example Source: https://github.com/agentmail-to/agentmail-toolkit/blob/main/_autodocs/api-reference/python-generic.md Shows how to instantiate the toolkit, get all tools, and call send_message by name. The result is the SDK send result containing message_id and thread_id. ```python from agentmail_toolkit import AgentMailToolkit toolkit = AgentMailToolkit() tools = toolkit.get_tools() by_name = {t.name: t for t in tools} result = by_name["send_message"].func( inbox_id="alice@example.com", to=["bob@example.com"], subject="Hello", text="Hi Bob", ) print(result) # SDK send result (message_id, thread_id) ``` -------------------------------- ### Install agentmail-toolkit with pip Source: https://github.com/agentmail-to/agentmail-toolkit/blob/main/python/README.md Install the AgentMail Toolkit package using pip. ```sh pip install agentmail-toolkit ``` -------------------------------- ### uploadFile usage example Source: https://github.com/agentmail-to/agentmail-toolkit/blob/main/_autodocs/api-reference/node-functions.md Example of using the upload_file tool from AgentMailToolkit. It uploads a base64-encoded PDF to the specified inbox path and logs the resulting file ID and status. ```ts import { AgentMailToolkit } from 'agentmail-toolkit' const tk = new AgentMailToolkit() const up = tk.getTools(['upload_file'])[0] const file = await up.func({ inboxId, path: 'reports/q3.pdf', content: Buffer.from(pdfBytes).toString('base64'), encoding: 'base64', contentType: 'application/pdf', }) console.log(file.fileId, file.status) // 'ready' ``` -------------------------------- ### AgentMailToolkit usage example with Agent and Runner Source: https://github.com/agentmail-to/agentmail-toolkit/blob/main/_autodocs/api-reference/python-openai.md Shows how to create an Agent with AgentMailToolkit tools and run it with a user prompt. Requires openai-agents>=0.6.1 and imports from agentmail_toolkit.openai. ```python from agentmail_toolkit.openai import AgentMailToolkit from agents import Agent, Runner agent = Agent( name="Email Agent", instructions="You are an email agent created by AgentMail that can send, receive, and manage emails.", tools=AgentMailToolkit().get_tools(), ) result = await Runner.run(agent, "List my inboxes and send a hello to bob@example.com") print(result.final_output) ``` -------------------------------- ### Create an OpenAI agent with AgentMail tools Source: https://github.com/agentmail-to/agentmail-toolkit/blob/main/python/README.md Initialize an OpenAI Agents SDK agent with AgentMail toolkit tools for email management. ```python from agentmail_toolkit.openai import AgentMailToolkit from agents import Agent agent = Agent( name="Email Agent", instructions="You are an agent created by AgentMail that can send, receive, and manage emails.", tools=AgentMailToolkit().get_tools(), ) ``` -------------------------------- ### Get AgentMail tools for generic use Source: https://github.com/agentmail-to/agentmail-toolkit/blob/main/node/README.md Retrieve AgentMail tools for frameworks not covered by dedicated exports. Each tool exposes name, description, paramsSchema, outputSchema, and a func. Failed calls throw a concise Error. ```typescript import { AgentMailToolkit } from 'agentmail-toolkit' const tools = new AgentMailToolkit().getTools() ``` -------------------------------- ### Basic usage: get_tools with names Source: https://github.com/agentmail-to/agentmail-toolkit/blob/main/_autodocs/api-reference/python-langchain.md Creates an AgentMailToolkit instance and retrieves tools by name. The example prints the names of the returned tools, which are 'list_inboxes' and 'send_message'. ```python from agentmail_toolkit.langchain import AgentMailToolkit from langchain.agents import create_agent # or your executor from langchain.tools import ToolException toolkit = AgentMailToolkit() tools = toolkit.get_tools(names=["list_inboxes", "send_message"]) print([t.name for t in tools]) # ['list_inboxes', 'send_message'] ``` -------------------------------- ### safeFunc usage example Source: https://github.com/agentmail-to/agentmail-toolkit/blob/main/_autodocs/api-reference/node-util.md Shows how to call safeFunc and handle the outcome, logging the error message and status code on failure or the result on success. ```ts const outcome = await safeFunc(sendMessage, client, args) if (outcome.isError) { console.error(outcome.result, outcome.statusCode) // '... (HTTP 400)', 400 } else { console.log(outcome.result) // SDK send result } ``` -------------------------------- ### Direct invocation error handling example Source: https://github.com/agentmail-to/agentmail-toolkit/blob/main/_autodocs/api-reference/python-openai.md Demonstrates calling on_invoke_tool directly and catching RuntimeError. The error message includes api_error_message text with an (HTTP ) suffix. ```python from agentmail_toolkit.openai import AgentMailToolkit tool = AgentMailToolkit().get_tools(names=["send_message"])[0] try: await tool.on_invoke_tool(ctx, '{"inbox_id": "alice@example.com", "to": ["bob@example.com"], "text": "hi"}') except RuntimeError as e: print(e) # api_error_message text: bounded, with (HTTP ) suffix ``` -------------------------------- ### Custom adapter example with get_tools Source: https://github.com/agentmail-to/agentmail-toolkit/blob/main/_autodocs/api-reference/python-toolkit.md Shows how to subclass Toolkit with a custom adapter that returns a dict per tool. Calling get_tools() with no arguments returns all tools in catalog order; passing names filters the result and silently ignores unknown names. ```python from agentmail_toolkit.toolkit import Toolkit from agentmail_toolkit.tools import Tool class EchoToolkit(Toolkit[dict]): # custom adapter — not a shipped adapter def _build_tool(self, tool: Tool) -> dict: return {"name": tool.name, "description": tool.description} tk = EchoToolkit() print(tk.get_tools()) # [{'name': 'list_inboxes', ...}, ...] print(tk.get_tools(names=["list_inboxes"])) # filtered; unknown names ignored ``` -------------------------------- ### Custom adapter subclassing BaseToolkit Source: https://github.com/agentmail-to/agentmail-toolkit/blob/main/_autodocs/api-reference/node-toolkit.md Shows how to create a custom adapter by subclassing BaseToolkit and implementing buildTool. The example wraps each tool's func to log the tool name before calling it. Note that BaseToolkit is source-internal and not exported as an npm subpath. ```TypeScript // Custom adapter: subclass and implement buildTool import { BaseToolkit } from './toolkit' // source-internal import type { AgentMailClient } from 'agentmail' import { type Tool } from './tools' class LoggingToolkit extends BaseToolkit<{ name: string; run: typeof Tool.prototype.func }> { protected buildTool(tool: Tool) { return { name: tool.name, run: (client: AgentMailClient, args: unknown) => { console.log(`calling ${tool.name}`) return tool.func(client, args as never) }, } } } ``` -------------------------------- ### Example: getTools returning AgentTool[] for pi-agent Source: https://github.com/agentmail-to/agentmail-toolkit/blob/main/_autodocs/api-reference/node-clawdbot.md Shows how to instantiate AgentMailToolkit and call getTools() to obtain an array of AgentTool objects. These tools can be passed to a pi-agent agent's tool list; failed calls surface as errored tool results via the framework's agent loop. ```typescript import { AgentMailToolkit } from 'agentmail-toolkit/clawdbot' const tools = new AgentMailToolkit().getTools() // tools: AgentTool[] — pass to a pi-agent agent's tool list; failed calls // surface as errored tool results via the framework's agent loop. ``` -------------------------------- ### Example: get_attachment with extraction Source: https://github.com/agentmail-to/agentmail-toolkit/blob/main/_autodocs/api-reference/python-functions.md Shows using get_attachment to fetch an attachment and print its download_url and extracted text. Extraction is best-effort: oversize, non-https, non-PDF/DOCX, or parse failures return the attachment without 'text' instead of raising. ```python from agentmail_toolkit.functions import get_attachment att = get_attachment( client, {"inbox_id": ..., "thread_id": ..., "attachment_id": ...}, ) print(att.download_url) print(getattr(att, "text", None)) # extracted PDF/DOCX text when applicable; absent otherwise # Extraction is best-effort: oversize / non-https / non-PDF-DOCX / parse failures # all return the attachment without `text` instead of raising. ``` -------------------------------- ### Example: send_message and list_inboxes Source: https://github.com/agentmail-to/agentmail-toolkit/blob/main/_autodocs/api-reference/python-functions.md Demonstrates using send_message and list_inboxes from the toolkit. Creates an AgentMail client, sends a message, and prints the resulting message_id and thread_id. ```python from agentmail import AgentMail from agentmail_toolkit.functions import send_message, list_inboxes client = AgentMail() result = send_message( client, {"inbox_id": "alice@example.com", "to": ["bob@example.com"], "text": "hi"}, ) print(result.message_id, result.thread_id) ``` -------------------------------- ### Error handling and direct tool execution with AgentMailToolkit Source: https://github.com/agentmail-to/agentmail-toolkit/blob/main/_autodocs/api-reference/node-ai-sdk.md Demonstrates error handling and non-trivial usage: inspecting the 'tool-error' part and calling a tool directly. Shows how to get a subset of tools by name and execute them, with errors surfacing as thrown Error objects with bounded messages. ```TypeScript import { AgentMailToolkit } from 'agentmail-toolkit/ai-sdk' import { type Tool } from 'ai' const toolkit = new AgentMailToolkit() const tools: Record = toolkit.getTools() const selected = toolkit.getTools(['send_message', 'list_inboxes']) // subset map // Direct execution — errors surface as thrown Error with bounded messages try { const id = await tools.list_inboxes.execute({ limit: 5 }) console.log(id.inboxes.length) } catch (err) { console.error((err as Error).message) } ``` -------------------------------- ### Get AgentMail tools for clawdbot Source: https://github.com/agentmail-to/agentmail-toolkit/blob/main/node/README.md Retrieve AgentMail tools for use with clawdbot. Failed tool calls throw; clawdbot's agent loop catches them and marks the result as errored. ```typescript import { AgentMailToolkit } from 'agentmail-toolkit/clawdbot' const tools = new AgentMailToolkit().getTools() ``` -------------------------------- ### errorMessage usage example Source: https://github.com/agentmail-to/agentmail-toolkit/blob/main/_autodocs/api-reference/node-util.md Shows how to call errorMessage in a catch block to log a concise error message, including the HTTP 429 rate-limit guidance. ```ts try { await somethingThatFails() } catch (err) { console.error(errorMessage(err)) // '... — mail quota ... (HTTP 429) — rate limited; wait before retrying' } ``` -------------------------------- ### Set AGENTMAIL_API_KEY environment variable Source: https://github.com/agentmail-to/agentmail-toolkit/blob/main/python/README.md Configure the AgentMail API key as an environment variable for authentication. ```sh export AGENTMAIL_API_KEY=your-api-key ``` -------------------------------- ### Error handling with ToolException Source: https://github.com/agentmail-to/agentmail-toolkit/blob/main/_autodocs/api-reference/python-langchain.md Shows how to catch ToolException when invoking a tool with invalid arguments. The example invokes send_message with an empty 'to' list, which is required by SendMessageParams, and prints the api_error_message text (e.g., containing 'HTTP 400'). ```python from agentmail_toolkit.langchain import AgentMailToolkit from langchain.tools import ToolException send = AgentMailToolkit().get_tools(names=["send_message"])[0] try: send.invoke({"inbox_id": "alice@example.com", "to": [], "text": "hi"}) # to is required by SendMessageParams except ToolException as e: print(e) # api_error_message text, e.g. '... (HTTP 400) ...' ``` -------------------------------- ### normalize usage example Source: https://github.com/agentmail-to/agentmail-toolkit/blob/main/_autodocs/api-reference/node-util.md Shows the output of normalize when given an object with a Date and an undefined property. The Date becomes an ISO string and the undefined property is removed. ```TypeScript const normalized = normalize({ sentAt: new Date('2026-01-01T00:00:00Z'), drop: undefined }) // { sentAt: '2026-01-01T00:00:00.000Z' } ``` -------------------------------- ### Example: Error handling when calling execute directly Source: https://github.com/agentmail-to/agentmail-toolkit/blob/main/_autodocs/api-reference/node-clawdbot.md Demonstrates calling execute directly on a send_message tool. The outcome.details contains the raw result with Date objects, while outcome.content[0].text is the JSON string. Errors are caught and logged with a concise bounded message. ```typescript import { AgentMailToolkit } from 'agentmail-toolkit/clawdbot' const send = new AgentMailToolkit().getTools(['send_message'])[0] try { const outcome = await send.execute('call_1', { inboxId: 'alice@example.com', to: ['bob@example.com'], subject: 'Hello', text: 'Hi', }) console.log(outcome.details) // raw result with Date objects console.log(outcome.content[0].text) // JSON string } catch (err) { console.error((err as Error).message) // concise bounded message } ``` -------------------------------- ### AgentMailToolkit class definition with _build_tool Source: https://github.com/agentmail-to/agentmail-toolkit/blob/main/_autodocs/api-reference/python-langchain.md Defines the AgentMailToolkit class that returns LangChain BaseTool instances. The _build_tool method wraps each tool's function, catching exceptions and raising ToolException with api_error_message. handle_tool_error is set post-construction because passing it to the tool() factory raises TypeError on the installed langchain version. ```python class AgentMailToolkit(Toolkit[BaseTool]): def __init__(self, client: Optional[AgentMail] = None): super().__init__(client) def _build_tool(self, tool: Tool): def runnable(**kwargs): try: return tool.func(self.client, kwargs) except Exception as e: raise ToolException(api_error_message(e)) from e built = langchain_tool( name_or_callable=tool.name, description=tool.description, args_schema=tool.params_schema, runnable=runnable, ) # handle_tool_error is a BaseTool field, not a tool()-factory kwarg — # passing it to tool() above raises TypeError on the installed # langchain version, so it's set post-construction instead. built.handle_tool_error = True return built ``` -------------------------------- ### List-shaped usage with langchain adapter Source: https://github.com/agentmail-to/agentmail-toolkit/blob/main/_autodocs/api-reference/node-toolkit.md Shows how to use the List-shaped toolkit from the langchain adapter. getTools returns an array of StructuredTool instances; unknown names are silently ignored, as shown by the 'does_not_exist' example returning length 1. ```TypeScript // List-shaped: generic / langchain / mcp / clawdbot import { AgentMailToolkit } from 'agentmail-toolkit/langchain' const all: StructuredTool[] = new AgentMailToolkit().getTools() const subset = new AgentMailToolkit().getTools(['list_inboxes', 'send_message']) // unknown names are ignored: const chosen = new AgentMailToolkit().getTools(['send_message', 'does_not_exist']) // length 1 ``` -------------------------------- ### Example: using api_error_message with ApiError Source: https://github.com/agentmail-to/agentmail-toolkit/blob/main/_autodocs/api-reference/python-util.md Shows how to call api_error_message on an exception from a client call. The output includes the HTTP status code and fix text when present. ```python from agentmail_toolkit.util import api_error_message try: client.inboxes.messages.send(...) except Exception as e: # ApiError from agentmail.core msg = api_error_message(e) print(msg) # '... (HTTP 429) — ' ``` -------------------------------- ### Example: bounded message for non-API exceptions Source: https://github.com/agentmail-to/agentmail-toolkit/blob/main/_autodocs/api-reference/python-util.md Demonstrates that non-API exceptions are still bounded to MAX_ERROR_BODY_LENGTH plus the truncation ellipsis. The assertion checks the length is 501 characters. ```python from agentmail_toolkit.util import api_error_message, MAX_ERROR_BODY_LENGTH # Non-API exceptions still come back bounded: msg = api_error_message(ValueError("x" * 10_000)) assert len(msg) == MAX_ERROR_BODY_LENGTH + 1 # 500 chars + truncation ellipsis ``` -------------------------------- ### AgentMailToolkit.__init__(client) Source: https://github.com/agentmail-to/agentmail-toolkit/blob/main/_autodocs/api-reference/python-openai.md Initializes a new AgentMailToolkit instance. The optional client parameter is bound into the tool functions when tools are invoked. ```APIDOC ## AgentMailToolkit.__init__(client) ### Description Initializes a new AgentMailToolkit instance. The optional client parameter is bound into the tool functions when tools are invoked. ### Method Constructor ### Parameters - **client** (Optional[AgentMail]) - Optional - An AgentMail client instance. Defaults to `AgentMail()`. ### Returns None ``` -------------------------------- ### joinLabs Source: https://github.com/agentmail-to/agentmail-toolkit/blob/main/_autodocs/api-reference/node-functions.md Joins the labs program for the organization. ```APIDOC ## joinLabs ### Description Joins the labs program for the organization. ### Implementation `client.organizations.joinLabs()` ``` -------------------------------- ### AgentMailToolkit.__init__ Source: https://github.com/agentmail-to/agentmail-toolkit/blob/main/_autodocs/api-reference/python-generic.md Initializes the AgentMailToolkit with an optional AgentMail client. The client is bound into every tool's func for the generic Python adapter. ```APIDOC ## AgentMailToolkit.__init__ ### Description Initializes the AgentMailToolkit with an optional AgentMail client. The client is bound into every tool's func for the generic Python adapter. ### Method Constructor ### Parameters - `client` (Optional[AgentMail]) - Optional - Client bound into every tool's func. Defaults to `AgentMail()`. ### Request Example ```python from agentmail_toolkit import AgentMailToolkit toolkit = AgentMailToolkit() ``` ``` -------------------------------- ### AgentMailToolkit usage with AgentSession Source: https://github.com/agentmail-to/agentmail-toolkit/blob/main/_autodocs/api-reference/python-livekit.md Shows how to create an AgentSession with the AgentMailToolkit's tools. Requires livekit-agents>=1.3.5 and an active AgentSession context for generate_reply to work. ```python from agentmail_toolkit.livekit import AgentMailToolkit from livekit.agents import AgentSession, Agent session = AgentSession( instructions="You are an email agent that manages inboxes.", tools=AgentMailToolkit().get_tools(), # Agent(Session) with the tools list... ) ``` -------------------------------- ### AgentMailToolkit constructor Source: https://github.com/agentmail-to/agentmail-toolkit/blob/main/_autodocs/api-reference/node-clawdbot.md Creates a new AgentMailToolkit instance for the clawdbot/pi-agent-core adapter. Inherits BaseToolkit's constructor and accepts an optional AgentMailClient. ```APIDOC ## AgentMailToolkit constructor ### Description Creates a new AgentMailToolkit instance for the clawdbot/pi-agent-core adapter. Inherits BaseToolkit's constructor and accepts an optional AgentMailClient. ### Method Constructor ### Endpoint `new AgentMailToolkit(client?: AgentMailClient)` ### Parameters #### Constructor Parameters - **client** (AgentMailClient) - Optional - The AgentMail client to use for tool execution. ### Request Example ```ts import { AgentMailToolkit } from 'agentmail-toolkit/clawdbot' const tools = new AgentMailToolkit() ``` ### Response #### Success Response Returns an `AgentMailToolkit` instance. #### Response Example ```ts const toolkit = new AgentMailToolkit() ``` ``` -------------------------------- ### AgentTool.execute(_toolCallId, args) Source: https://github.com/agentmail-to/agentmail-toolkit/blob/main/_autodocs/api-reference/node-clawdbot.md Executes a tool with the given arguments. Parses arguments using the tool's paramsSchema, runs the tool function, and returns a result object with content and details. Throws an Error with a formatted message on failure. ```APIDOC ## AgentTool.execute(_toolCallId, args) ### Description Executes a tool with the given arguments. Parses arguments using the tool's paramsSchema, runs the tool function, and returns a result object with content and details. Throws an Error with a formatted message on failure. ### Method Method ### Endpoint `execute(_toolCallId: string, args: unknown): Promise<{ content: Array<{ type: 'text', text: string }>, details: unknown }>` ### Parameters #### Parameters - **_toolCallId** (string) - Required - The tool call identifier. - **args** (object) - Required - The arguments to pass to the tool. Must match the tool's paramsSchema. ### Request Example ```ts const send = new AgentMailToolkit().getTools(['send_message'])[0] const outcome = await send.execute('call_1', { inboxId: 'alice@example.com', to: ['bob@example.com'], subject: 'Hello', text: 'Hi', }) ``` ### Response #### Success Response Returns an object with: - **content** (Array) - Array containing a single object with `type: 'text'` and `text` (JSON string of the result). - **details** (unknown) - The raw result from the tool function. #### Response Example ```ts { content: [{ type: 'text', text: '{"id":"..."}' }], details: { id: '...', date: Date } } ``` ### Error Handling Throws an `Error` with a formatted message on tool execution failure. ``` -------------------------------- ### AiSdkTool.execute(args) Source: https://github.com/agentmail-to/agentmail-toolkit/blob/main/_autodocs/api-reference/node-ai-sdk.md Executes the underlying tool with the given arguments, normalizing the result (Date to ISO string) and throwing an Error on failure so the AI SDK produces a tool-error part. ```APIDOC ## execute(args): Promise ### Description Executes the tool with the provided arguments. The result is normalized (Date objects converted to ISO strings) before being returned. If the tool throws, the error is rethrown as a new Error with a bounded message, allowing the AI SDK to emit a `tool-error` content part. ### Method Function call ### Endpoint `tool.execute(args)` where `tool` is an `AiSdkTool` from `getTools()` ### Parameters #### Request Body - **args** (object) - Required - Arguments matching the tool's `inputSchema`. ### Returns - **Promise** - The normalized result of the tool execution. ### Throws - **Error** - If the underlying tool fails, an Error with a bounded message is thrown. ### Example ```ts const tools = new AgentMailToolkit().getTools() try { const result = await tools.list_inboxes.execute({ limit: 5 }) console.log(result.inboxes.length) } catch (err) { console.error((err as Error).message) } ``` ``` -------------------------------- ### AgentMailToolkit constructor Source: https://github.com/agentmail-to/agentmail-toolkit/blob/main/_autodocs/api-reference/python-langchain.md Creates a new AgentMailToolkit instance. Optionally accepts an AgentMail client that will be bound into the tool functions. ```APIDOC ## AgentMailToolkit(client) ### Description Creates a new AgentMailToolkit instance. Optionally accepts an AgentMail client that will be bound into the tool functions. ### Parameters - **client** (Optional[AgentMail]) - Optional - The AgentMail client to use. Defaults to a new AgentMail() instance. ### Example ```python from agentmail_toolkit.langchain import AgentMailToolkit toolkit = AgentMailToolkit() ``` ``` -------------------------------- ### connectApp Source: https://github.com/agentmail-to/agentmail-toolkit/blob/main/_autodocs/api-reference/node-functions.md Connects an application. Retries are disabled to prevent duplicate live sign-in sessions. ```APIDOC ## connectApp ### Description Connects an application. Retries are disabled to prevent duplicate live sign-in sessions. ### Parameters - `appId` (string) - Required - The application ID. - `body` (object) - Required - Connection details. ### Implementation `client.apps.connect(appId, body, { maxRetries: 0 })` ``` -------------------------------- ### AgentMailToolkit class implementation Source: https://github.com/agentmail-to/agentmail-toolkit/blob/main/_autodocs/api-reference/python-openai.md Defines the AgentMailToolkit class that returns agents.FunctionTool objects. The _build_tool method wraps catalog tools with async invocation, error handling, and JSON schema configuration. ```python class AgentMailToolkit(Toolkit[FunctionTool]): def __init__(self, client: Optional[AgentMail] = None): super().__init__(client) def _build_tool(self, tool: Tool): async def on_invoke_tool(ctx: RunContextWrapper, input_str: str): try: result = await asyncio.to_thread( tool.func, self.client, json.loads(input_str) ) except Exception as e: raise RuntimeError(api_error_message(e)) from e return "OK" if result is None else result.model_dump_json() params_json_schema = tool.params_schema.model_json_schema() params_json_schema["additionalProperties"] = False return FunctionTool( name=tool.name, description=tool.description, params_json_schema=params_json_schema, on_invoke_tool=on_invoke_tool, ) ``` -------------------------------- ### AgentMailToolkit constructor Source: https://github.com/agentmail-to/agentmail-toolkit/blob/main/_autodocs/api-reference/python-livekit.md Creates a new AgentMailToolkit instance. Optionally accepts an AgentMail client; if not provided, a default client is created. ```APIDOC ## AgentMailToolkit(client: Optional[AgentMail] = None) ### Description Creates a new AgentMailToolkit instance. Optionally accepts an AgentMail client; if not provided, a default client is created. ### Parameters - **client** (Optional[AgentMail]) - Optional - The AgentMail client to use. Defaults to `AgentMail()`. ### Returns An `AgentMailToolkit` instance. ### Example ```python from agentmail_toolkit.livekit import AgentMailToolkit toolkit = AgentMailToolkit() ``` ``` -------------------------------- ### new AgentMailToolkit(client?) Source: https://github.com/agentmail-to/agentmail-toolkit/blob/main/_autodocs/api-reference/node-index.md Creates a new AgentMailToolkit instance. The optional client is bound into every tool's func. If not provided, a default AgentMailClient is created using the AGENTMAIL_API_KEY environment variable. ```APIDOC ## Constructor: new AgentMailToolkit(client?) ### Description Creates a new AgentMailToolkit instance. The optional client is bound into every tool's func. If not provided, a default AgentMailClient is created using the AGENTMAIL_API_KEY environment variable. ### Parameters - `client` (AgentMailClient) - Optional - Client bound into every tool's func. Defaults to `new AgentMailClient()`. ### Example ```ts import { AgentMailToolkit } from 'agentmail-toolkit' const toolkit = new AgentMailToolkit() // AGENTMAIL_API_KEY from env ``` ``` -------------------------------- ### Toolkit.__init__(client: Optional[AgentMail] = None) Source: https://github.com/agentmail-to/agentmail-toolkit/blob/main/_autodocs/api-reference/python-toolkit.md Initializes a new Toolkit instance. Builds the internal tool registry by adapting each catalog tool via the abstract _build_tool method, and binds the provided AgentMail client (or a default one) to all adapted tools. ```APIDOC ## Toolkit.__init__(client: Optional[AgentMail] = None) ### Description Initializes a new Toolkit instance. Builds the internal tool registry by adapting each catalog tool via the abstract _build_tool method, and binds the provided AgentMail client (or a default one) to all adapted tools. ### Method Constructor ### Parameters - **client** (Optional[AgentMail]) - Optional - An `agentmail` SDK client to bind into every adapted tool. Defaults to `AgentMail()`, which reads the `AGENTMAIL_API_KEY` environment variable. ### Returns None ### Example ```python from agentmail_toolkit.toolkit import Toolkit from agentmail_toolkit.tools import Tool class EchoToolkit(Toolkit[dict]): def _build_tool(self, tool: Tool) -> dict: return {"name": tool.name, "description": tool.description} tk = EchoToolkit() ``` ``` -------------------------------- ### get_tools(names) Source: https://github.com/agentmail-to/agentmail-toolkit/blob/main/_autodocs/api-reference/python-langchain.md Returns a list of LangChain BaseTool instances for the requested tool names. Inherited from the Toolkit base class. ```APIDOC ## get_tools(names) ### Description Returns a list of LangChain BaseTool instances for the requested tool names. Inherited from the Toolkit base class. ### Parameters - **names** (Optional[List[str]]) - Optional - List of tool names to retrieve. If None, returns all tools. ### Returns - **list[BaseTool]** - List of LangChain BaseTool instances. ### Example ```python from agentmail_toolkit.langchain import AgentMailToolkit toolkit = AgentMailToolkit() tools = toolkit.get_tools(names=["list_inboxes", "send_message"]) print([t.name for t in tools]) # ['list_inboxes', 'send_message'] ``` ``` -------------------------------- ### AgentMailToolkit.get_tools Source: https://github.com/agentmail-to/agentmail-toolkit/blob/main/_autodocs/api-reference/python-generic.md Returns a list of Tool objects from the toolkit. The names parameter filters which tools to return, but the order follows catalog order, not request order. ```APIDOC ## AgentMailToolkit.get_tools ### Description Returns a list of Tool objects from the toolkit. The names parameter filters which tools to return, but the order follows catalog order, not request order. ### Method Function ### Parameters - `names` (Optional[List[str]]) - Optional - List of tool names to return. If None, returns all tools. ### Returns - `list[Tool]` - List of Tool objects. ### Request Example ```python from agentmail_toolkit import AgentMailToolkit toolkit = AgentMailToolkit() tools = toolkit.get_tools() by_name = {t.name: t for t in tools} ``` ``` -------------------------------- ### AgentMailToolkit constructor Source: https://github.com/agentmail-to/agentmail-toolkit/blob/main/_autodocs/api-reference/node-langchain.md Creates a new AgentMailToolkit instance. Inherits BaseToolkit's constructor and accepts an optional AgentMailClient. ```APIDOC ## Constructor ### Description Creates a new AgentMailToolkit instance. Inherits BaseToolkit's constructor and accepts an optional AgentMailClient. ### Signature `new AgentMailToolkit(client?: AgentMailClient)` ### Parameters - **client** (AgentMailClient) - Optional - The AgentMail client to use for API calls. ### Example ```ts import { AgentMailToolkit } from 'agentmail-toolkit/langchain' const toolkit = new AgentMailToolkit() ``` ``` -------------------------------- ### AgentMailToolkit._build_tool(tool) Source: https://github.com/agentmail-to/agentmail-toolkit/blob/main/_autodocs/api-reference/python-openai.md Builds a FunctionTool object from a catalog Tool model. The returned FunctionTool is ready to be used with the OpenAI Agents SDK. ```APIDOC ## AgentMailToolkit._build_tool(tool) ### Description Builds a FunctionTool object from a catalog Tool model. The returned FunctionTool is ready to be used with the OpenAI Agents SDK. ### Method _build_tool ### Parameters - **tool** (Tool) - Required - A catalog pydantic model representing a tool. ### Returns FunctionTool with the following fields: - **name** (str) - The tool name. - **description** (str) - The tool description. - **params_json_schema** (dict) - The tool's parameter schema with `additionalProperties` set to `False`. - **on_invoke_tool** (async function) - Async function that takes `(ctx: RunContextWrapper, input_str: str)` and returns a string. It parses the input JSON, runs the tool function off the event loop, and returns `"OK"` if the result is `None`, otherwise the result's JSON dump. Raises `RuntimeError` with an API error message on failure. ``` -------------------------------- ### Tool.func Source: https://github.com/agentmail-to/agentmail-toolkit/blob/main/_autodocs/api-reference/python-generic.md Calls the underlying tool function with the bound client. The function accepts keyword arguments validated against the tool's params_schema and returns the SDK result. ```APIDOC ## Tool.func ### Description Calls the underlying tool function with the bound client. The function accepts keyword arguments validated against the tool's params_schema and returns the SDK result. ### Method Function ### Parameters - `**kwargs` - Required - Keyword arguments matching the tool's params_schema. Unknown kwargs flow to the SDK call and raise TypeError or SDK validation errors. ### Returns - The SDK result (e.g., send result with message_id, thread_id). ### Request Example ```python from agentmail_toolkit import AgentMailToolkit toolkit = AgentMailToolkit() tools = toolkit.get_tools() by_name = {t.name: t for t in tools} result = by_name["send_message"].func( inbox_id="alice@example.com", to=["bob@example.com"], subject="Hello", text="Hi Bob", ) print(result) # SDK send result (message_id, thread_id) ``` ### Error Handling A failed tool call raises the SDK's `ApiError` (or another exception) unwrapped. The generic adapter does not convert to framework error types. ```python from agentmail_toolkit import AgentMailToolkit from agentmail.core import ApiError send = AgentMailToolkit().get_tools(names=["send_message"])[0] try: send.func(inbox_id="alice@example.com", to=["nobody@example.com"], text="hi") except ApiError as e: print(e.status_code, e.body) # raw API error; the generic binding does not re-wrap ``` ``` -------------------------------- ### Create agent with AgentMailToolkit Source: https://github.com/agentmail-to/agentmail-toolkit/blob/main/_autodocs/api-reference/node-langchain.md Shows how to instantiate AgentMailToolkit and pass its tools to a LangChain createAgent call. Requires the optional peer dependency langchain ^1.2.0. ```ts import { AgentMailToolkit } from 'agentmail-toolkit/langchain' import { createAgent } from 'langchain' const agent = createAgent({ model: 'openai:gpt-4o', tools: new AgentMailToolkit().getTools(), }) ``` -------------------------------- ### buildTool(tool: Tool): StructuredTool Source: https://github.com/agentmail-to/agentmail-toolkit/blob/main/_autodocs/api-reference/node-langchain.md Builds a LangChain StructuredTool from a catalog entry. The tool's function is wrapped to return a JSON-stringified result and to throw a plain Error on failure. ```APIDOC ## buildTool(tool: Tool): StructuredTool ### Description Builds a LangChain StructuredTool from a catalog entry. The tool's function is wrapped to return a JSON-stringified result and to throw a plain Error on failure. ### Method buildTool ### Parameters - **tool** (Tool) - Required - Catalog entry containing name, description, paramsSchema, and function. ### Returns - **StructuredTool** - A DynamicStructuredTool with the following properties: - **name** (string) - The tool's name. - **description** (string) - The tool's description. - **schema** (ZodObjectAny) - The tool's paramsSchema; LangChain generates the args schema from it. - **invoke/call** (function) - Returns a Promise that resolves to a JSON-stringified result of the bound SDK call. ### Throws - **Error** - If the underlying SDK call fails, the promise rejects with a plain Error containing the error message. ### Example ```ts import { AgentMailToolkit } from 'agentmail-toolkit/langchain' const send = new AgentMailToolkit().getTools(['send_message'])[0] try { const result = await send.invoke({ inboxId: 'alice@example.com', to: ['bob@example.com'], text: 'Hello', }) console.log(result) // JSON string, pretty-printed } catch (err) { console.error((err as Error).message) // bounded text, never the SDK dump } ``` ``` -------------------------------- ### AgentMailToolkit class with _build_tool Source: https://github.com/agentmail-to/agentmail-toolkit/blob/main/_autodocs/api-reference/python-generic.md Framework-agnostic toolkit that adapts catalog tools into pydantic Tool objects. The _build_tool method closes over the client, so unknown kwargs flow to the SDK call and raise TypeError or SDK validation errors. ```python class AgentMailToolkit(Toolkit[Tool]): def __init__(self, client: Optional[AgentMail] = None): super().__init__(client) def _build_tool(self, tool: BaseTool): def func(**kwargs): return tool.func(self.client, kwargs) return Tool( name=tool.name, description=tool.description, params_schema=tool.params_schema, func=func, ) ``` -------------------------------- ### async invoke(name, client, args, options?) Source: https://github.com/agentmail-to/agentmail-toolkit/blob/main/_autodocs/api-reference/node-mcp.md Dispatches a tool call by name using the module-level toolsByName map. Returns an error result for unknown tools and never throws. The client parameter bypasses the construction-time bound client, enabling a hosted MCP server to serve many users. ```TypeScript async invoke( name: string, client: AgentMailClient, args: Record, options?: ToolCallOptions ): Promise { const tool = toolsByName.get(name) if (!tool) { return { content: [{ type: 'text' as const, text: `Unknown tool: ${name}` }], isError: true, } } return runTool(tool, client, args, options) } ``` -------------------------------- ### get_tools(names: Optional[List[str]] = None) -> list[FunctionTool] Source: https://github.com/agentmail-to/agentmail-toolkit/blob/main/_autodocs/api-reference/python-livekit.md Returns a list of LiveKit FunctionTool instances for the toolkit. Optionally filters by tool names. ```APIDOC ## get_tools(names: Optional[List[str]] = None) -> list[FunctionTool] ### Description Returns a list of LiveKit FunctionTool instances for the toolkit. Optionally filters by tool names. ### Parameters - **names** (Optional[List[str]]) - Optional - List of tool names to include. If None, all tools are returned. ### Returns A list of `FunctionTool` instances. ### Example ```python from agentmail_toolkit.livekit import AgentMailToolkit tools = AgentMailToolkit().get_tools() ``` ``` -------------------------------- ### AgentMailToolkit class extending ListToolkit Source: https://github.com/agentmail-to/agentmail-toolkit/blob/main/_autodocs/api-reference/node-clawdbot.md Defines the AgentMailToolkit class that extends ListToolkit. The buildTool method converts each Tool into a pi-agent-core AgentTool, parsing arguments with tool.paramsSchema and returning content and details. On error, it throws a new Error with a formatted message. ```typescript export class AgentMailToolkit extends ListToolkit { protected buildTool(tool: Tool): AgentTool { return { name: tool.name, label: tool.name, description: tool.description, parameters: zodToJSONSchema(tool), execute: async (_toolCallId, args) => { try { const result = await tool.func(this.client, tool.paramsSchema.parse(args)) return { content: [{ type: 'text', text: JSON.stringify(result) }], details: result, } } catch (err) { throw new Error(errorMessage(err)) } }, } } } ``` -------------------------------- ### AgentMailToolkit class implementation Source: https://github.com/agentmail-to/agentmail-toolkit/blob/main/_autodocs/api-reference/node-langchain.md Defines the AgentMailToolkit class extending ListToolkit. The buildTool method wraps each tool's function with langchainTool, stringifying results and throwing plain Errors on failure. Note: results are not normalized or validated against outputSchema. ```ts import { type StructuredTool, tool as langchainTool } from 'langchain' import { ListToolkit } from './toolkit.js' import { type Tool } from './tools.js' import { errorMessage } from './util.js' export class AgentMailToolkit extends ListToolkit { protected buildTool(tool: Tool): StructuredTool { return langchainTool( async (args: Record) => { try { return JSON.stringify(await tool.func(this.client, args), null, 2) } catch (err) { throw new Error(errorMessage(err)) } }, { name: tool.name, description: tool.description, schema: tool.paramsSchema, } ) } } ``` -------------------------------- ### Tool.func(args) Source: https://github.com/agentmail-to/agentmail-toolkit/blob/main/_autodocs/api-reference/node-index.md Executes the tool with the given arguments and returns the raw SDK result. The result is not stripped to outputSchema and may contain real Date objects. Throws an Error with a bounded message on failure. ```APIDOC ## Method: Tool.func(args) ### Description Executes the tool with the given arguments and returns the raw SDK result. The result is not stripped to outputSchema and may contain real Date objects. Throws an Error with a bounded message on failure. ### Parameters - `args` (Record) - Required - Arguments matching the tool's paramsSchema. ### Returns - `Promise` - The raw SDK result. For example, `send_message` returns `{ messageId: '<...>', threadId: '...' }`. ### Throws - `Error` - With a bounded message from `errorMessage` on any failed tool call. Argument validation is the caller's responsibility. ### Example ```ts import { AgentMailToolkit } from 'agentmail-toolkit' const toolkit = new AgentMailToolkit() const send = toolkit.getTools(['send_message'])[0] const result = await send.func({ inboxId: 'alice@example.com', to: ['bob@example.com'], subject: 'Hello', text: 'Hi Bob', }) console.log(result) // { messageId: '<...>', threadId: '...' } ``` ``` -------------------------------- ### AgentMailToolkit class with _build_tool method Source: https://github.com/agentmail-to/agentmail-toolkit/blob/main/_autodocs/api-reference/python-livekit.md Defines the AgentMailToolkit class that returns LiveKit FunctionTool instances. The _build_tool method creates an async function that runs the tool's function off the event loop, sends a status update via generate_reply, and raises ToolError on failure. ```python class AgentMailToolkit(Toolkit[FunctionTool]): def __init__(self, client: Optional[AgentMail] = None): super().__init__(client) def _build_tool(self, tool: Tool): async def f(raw_arguments: dict[str, object], context: RunContext): async def _status_update(): await context.session.generate_reply( instructions=f"Inform the user that you are doing the following: {tool.description}" ) status_update_task = asyncio.create_task(_status_update()) try: result = await asyncio.to_thread(tool.func, self.client, raw_arguments) return "OK" if result is None else result.model_dump_json() except Exception as e: raise ToolError(api_error_message(e)) finally: status_update_task.cancel() return function_tool( f=f, name=tool.name, description=tool.description, raw_schema={ "type": "function", "name": tool.name, "description": tool.description, "parameters": tool.params_schema.model_json_schema(), }, ) ``` -------------------------------- ### listAccounts Source: https://github.com/agentmail-to/agentmail-toolkit/blob/main/_autodocs/api-reference/node-functions.md Lists accounts. If an appId is provided, it fans out to the per-app route; otherwise, it lists all accounts. ```APIDOC ## listAccounts ### Description Lists accounts. If an appId is provided, it fans out to the per-app route; otherwise, it lists all accounts. ### Parameters - `appId` (string) - Optional - The application ID to list accounts for. - `options` (object) - Optional - Additional options for the list operation. ### Implementation `appId === undefined ? client.accounts.list(options) : client.apps.listAccounts(appId, options)` ``` -------------------------------- ### AgentMailToolkit class extending ListToolkit Source: https://github.com/agentmail-to/agentmail-toolkit/blob/main/_autodocs/api-reference/node-mcp.md Defines the MCP adapter class. Each tool's callback runs runTool with the client bound at construction; errors are signaled via isError: true, never thrown. ```TypeScript export class AgentMailToolkit extends ListToolkit { protected buildTool(tool: Tool): McpTool { return { name: tool.name, title: tool.title, description: tool.description, inputSchema: tool.paramsSchema.shape, outputSchema: tool.outputSchema.shape, callback: async (args) => runTool(tool, this.client, args as Record), annotations: tool.annotations, } } } ``` -------------------------------- ### AgentMailToolkit class implementation extending MapToolkit Source: https://github.com/agentmail-to/agentmail-toolkit/blob/main/_autodocs/api-reference/node-ai-sdk.md Defines the AgentMailToolkit class that extends MapToolkit. The buildTool method converts a Tool catalog entry into an AiSdkTool with description, inputSchema, outputSchema, and an execute function that normalizes results and rethrows errors as Error objects to produce the native 'tool-error' content part. ```TypeScript import { type Tool as AiSdkTool } from 'ai' import { MapToolkit } from './toolkit.js' import { type Tool } from './tools.js' import { errorMessage, normalize } from './util.js' export class AgentMailToolkit extends MapToolkit { protected buildTool(tool: Tool): AiSdkTool { return { description: tool.description, inputSchema: tool.paramsSchema, outputSchema: tool.outputSchema, execute: async (args) => { try { return normalize(await tool.func(this.client, args)) } catch (err) { throw new Error(errorMessage(err)) } }, } } } ``` -------------------------------- ### Basic call with AgentMailToolkit Source: https://github.com/agentmail-to/agentmail-toolkit/blob/main/_autodocs/api-reference/node-index.md Creates a toolkit instance using AGENTMAIL_API_KEY from env, retrieves all tools, finds 'send_message', and calls its func with inboxId, to, subject, and text. Logs the result containing messageId and threadId. ```ts import { AgentMailToolkit } from 'agentmail-toolkit' const toolkit = new AgentMailToolkit() // AGENTMAIL_API_KEY from env const tools = toolkit.getTools() const send = tools.find((t) => t.name === 'send_message')! const result = await send.func({ inboxId: 'alice@example.com', to: ['bob@example.com'], subject: 'Hello', text: 'Hi Bob', }) console.log(result) // { messageId: '<...>', threadId: '...' } ``` -------------------------------- ### Reading a catalog entry with an adapter Source: https://github.com/agentmail-to/agentmail-toolkit/blob/main/_autodocs/api-reference/node-tools.md Shows what an adapter reads from a catalog entry, including paramsSchema, outputSchema, and annotations. Note that destructiveHint is true for send_message because emailing is irreversible. ```typescript // What an adapter reads from a catalog entry import { tools } from './tools.js' const send = tools.find((t) => t.name === 'send_message')! send.paramsSchema // ZodObject — zod .parse(args) before calling send.func send.outputSchema // ZodObject — validate/normalize results against it send.annotations.destructiveHint // true — emailing is irreversible ``` -------------------------------- ### getTools(names?: string[]): Tool[] Source: https://github.com/agentmail-to/agentmail-toolkit/blob/main/_autodocs/api-reference/node-index.md Returns an array of adapted Tool objects. If names is provided, only tools with those names are returned. Each tool contains name, description, paramsSchema, outputSchema, and a func that executes the tool. ```APIDOC ## Method: getTools(names?: string[]): Tool[] ### Description Returns an array of adapted Tool objects. If names is provided, only tools with those names are returned. Each tool contains name, description, paramsSchema, outputSchema, and a func that executes the tool. ### Parameters - `names` (string[]) - Optional - Array of tool names to filter. If omitted, all tools are returned. ### Returns - `Tool[]` - Array of Tool objects with the following fields: - `name` (string) - Tool name, e.g. `'send_message'` - `description` (string) - Prompt-facing description - `paramsSchema` (z.ZodObject) - Zod input schema (e.g. `SendMessageParams`) - `outputSchema` (z.ZodObject) - Zod output contract (e.g. `SendMessageResponseSchema`) - `func` ((args: Record) => Promise) - Executes the tool and returns the raw SDK result ### Example ```ts import { AgentMailToolkit } from 'agentmail-toolkit' const toolkit = new AgentMailToolkit() const tools = toolkit.getTools() const send = tools.find((t) => t.name === 'send_message')! ``` ```