---
name: tools
description: "Give your agents capabilities through tools (function calling). Helps you identify what your agent needs to do, create tool definitions, and attach them to config variations."
license: Apache-2.0
compatibility: Requires the remotely hosted LaunchDarkly MCP server. Application code examples use `launchdarkly-ai-server` 1.0.0+ (Python) or `@launchdarkly/ai-node` 1.0.0+ (Node.js).
metadata:
  author: launchdarkly
  version: "1.1.0-experimental"
title: tools
canonical_url: https://skilld.dev/gh/launchdarkly/ai-tooling/tools
last_updated: 2026-11-18T14:03:20.000Z
---

> Index of every page on this site: [llms.txt](https://skilld.dev/llms.txt)

> **Skill from skilld.dev.** Follow the user's requested action.
> If the user asked to fork this Skill, follow the fork workflow below. Do not execute the Skill instructions while copying it.
> Otherwise, follow the instructions below for this session. You do not need to install anything.
>
> Supporting files, fetch one when the Skill refers to it: [README.md](https://skilld.dev/api/skills-raw/launchdarkly/ai-tooling/tools/README.md).
>
> If the user asked to install this Skill, run `npx skilld install launchdarkly/ai-tooling/tools`. Install writes the Skill files into the project, so every session loads them.
>
> ## Fork workflow
>
> A fork creates an editable local Skill with its original author and licence. The request authorizes copying and local installation.
> 1. Check `./skills/tools`, the project lockfile, and selected Agent targets together. If the local directory or installed Skill exists, stop. Never overwrite an existing directory or Agent target.
> 2. Read [source metadata](https://skilld.dev/api/v1/skills/launchdarkly/ai-tooling/tools) once. Use sourceUrl, sourceCommit, skillPath, sourceGone, and license. If the source is gone or its path is missing, stop. If license is null, read licence files at the source commit.
> 3. Fetch only the source commit into a temporary Git repository. Do not clone full history. Derive repository_url from sourceUrl, including repository renames. If sourceCommit is absent, resolve the sourceUrl ref once. Set source_commit to that actual commit. Run these commands in one shell call:
>
> ```sh
> git init --quiet "$temporary_dir"
> git -C "$temporary_dir" fetch --quiet --depth=1 "$repository_url" "$source_commit"
> git -C "$temporary_dir" checkout --quiet --detach FETCH_HEAD
> ```
>
> Read applicable licence declarations and notices at that commit. If copying is not permitted, report the restriction and stop.
> 4. Inspect source entries together, then copy the directory containing skillPath into `./skills/tools`. Use the user's path if selected. Keep the original SKILL.md, relative links, scripts, binary assets, and executable modes. Exclude .git metadata. Reject symlinks and paths outside the Skill directory. After checking entries, use cp -a where available. A regular source directory needs no custom copy script. Do not save this page wrapper as SKILL.md.
> Preserve author credit, notices, and applicable licence files from repository or parent directories. Add PROVENANCE.md with the Skill page, source URL, actual commit, original path, and licence. Retain any existing PROVENANCE.md and record new provenance separately. Batch source inspection, copying, and provenance work where practical.
> 5. In the project root, run `skilld install ./skills/tools --mode copy --plain`. If skilld is unavailable, use `npx skilld install ./skills/tools --mode copy --plain`. This known command needs no help lookup. Install does not support --json. Use detected Agent targets, or add --agent for the targets the user selected. Install the local path, never the upstream selector. If installation fails, preserve the local copy and report the exact failure.
> 6. Confirm the local lockfile source and installed Agent copies once. Report the local path, actual commit, and Agent targets. After edits, reinstall the same local path. Upstream updates must not replace it. Do not publish or push unless the user asks.

# Config Tools

You're using a skill that will guide you through adding capabilities to your agents through tools (function calling). Your job is to identify what your agent needs to do, create tool definitions, attach them to variations, and verify they work.

## Prerequisites

This skill requires the remotely hosted LaunchDarkly MCP server to be configured in your environment.

**Required MCP tools:**
- `create-ai-tool` -- create a new tool definition with a schema
- `update-agent-config` with `resource: "variation"` -- attach tools to a config variation
- `get-agent-configs` -- verify tools are attached to the variation

**Optional MCP tools:**
- `get-ai-tools` -- browse existing tools in the project; with `toolKey`, inspect one tool's schema

## Core Principles

1. **Start with Capabilities**: Think about what your agent needs to do before creating tools
2. **Framework Matters**: LangGraph/CrewAI often auto-generate schemas; OpenAI SDK needs manual schemas
3. **Create Before Attach**: Tools must exist before you can attach them to variations
4. **Verify**: The agent fetches the config to confirm attachment
5. **Complete the Full Workflow**: Listing existing tools is a discovery step, not the end goal. After listing, always proceed to create the requested tool, attach it, and verify. Do not stop after exploration.

## Workflow

### Step 1: Identify Needed Capabilities

What should the agent be able to do?
- Query databases, call APIs, perform calculations, send notifications
- Check what exists in the codebase (API clients, functions)
- Consider framework: LangGraph/LangChain auto-generate schemas; direct SDK needs manual schemas

If the user asks to check existing tools first, or you have no codebase context about what tools exist, follow this exact order:
1. `get-ai-tools` -- explore what exists
2. `create-ai-tool` -- create the new tool (with a key different from existing ones)
3. `update-agent-config` with `resource: "variation"` -- attach it
4. `get-agent-configs` -- verify

Call `get-ai-tools` as your **first** tool call before any creation. Never stop after listing alone -- always proceed through all four steps.

### Step 2: Create Tools

Use `create-ai-tool` with:
- `key` -- unique identifier for the tool
- `description` -- clear description (the LLM uses this to decide when to call the tool)
- `schema` -- raw JSON Schema (do NOT use the OpenAI function calling wrapper):

```json
{
  "type": "object",
  "properties": {
    "query": {"type": "string", "description": "Search query"},
    "limit": {"type": "integer", "default": 10}
  },
  "required": ["query"]
}
```

### Step 3: Attach to Variation

Use `update-agent-config` with `resource: "variation"` to attach tools. **Pass only the `tools` field** (plus `projectKey`, `configKey`, `variationKey`, and `confirm`). Do not bundle `instructions`, `messages`, `model`, or `parameters` into this PATCH unless the user has explicitly asked you to also update those fields. Those fields may have been edited in the LaunchDarkly UI since the variation was created, and including them in a tool-attachment PATCH will silently clobber the UI edits.

```json
{
  "projectKey": "my-project",
  "configKey": "support-chatbot",
  "resource": "variation",
  "variationKey": "default",
  "tools": [
    {"key": "search-knowledge-base", "version": 1}
  ],
  "confirm": true
}
```

If you observe a UI-clear bug where attaching tools wipes other fields, **do not work around it by re-sending those fields from the previous `get-agent-configs` response** — that masks the bug and can resurrect stale values that the user has since edited. Report the bug instead.

### Step 4: Verify

1. Use `get-ai-tools` to confirm the tool exists with a valid schema
2. Use `get-agent-configs` to confirm the tool is attached to the variation (check `tools` in the variation's output)

**Report results:**
- Tool created with valid schema
- Tool attached to variation
- Flag any issues

## Implement the tools in your application

LaunchDarkly stores each tool's schema and attaches it to the variation. Your application supplies the function that runs when the model calls the tool. With the AI SDK (`launchdarkly-ai-server` for Python, `@launchdarkly/ai-node` for Node.js) and a provider handler package, that function is all you write. The handler converts the schemas to the provider's format, runs the tool loop, and records a `$ld:ai:tool_call` event for every call. You don't convert schemas, write a loop, or call a tracker.

Pass the functions as `tool_handlers` (Python) or `toolHandlers` (Node.js), keyed by the tool key you created in Step 2:

```python
from launchdarkly_ai_server import config
from launchdarkly_ai_openai_messages import create_openai_messages_handler

def search_knowledge_base(args):
    # args is one dict of the arguments the model sent, matching the tool's schema
    return kb.search(args["query"], limit=args.get("limit", 10))

result = await config(
    key="support-chatbot",
    handler=[create_openai_messages_handler()],
    tool_handlers={"search-knowledge-base": search_knowledge_base},
).invoke(user_input, {"kind": "user", "key": "user-123"})
```

```typescript
import { config } from '@launchdarkly/ai-node';
import { createOpenAIMessagesHandler } from '@launchdarkly/ai-openai-messages';

const result = await config({
  key: 'support-chatbot',
  handler: [createOpenAIMessagesHandler()],
  toolHandlers: {
    'search-knowledge-base': async (args) => kb.search(args.query, args.limit ?? 10),
  },
}).invoke(userInput, { kind: 'user', key: 'user-123' });
```

Rules for tool functions:

- **Keys must match exactly.** The key in `tool_handlers` must equal the tool key on the variation, including case. The handlers offer the model only the variation's tools that have a function, so a tool whose key doesn't match is silently left out of the call.
- **One argument.** The function receives a single dict (Python) or object (Node.js) of arguments, not keyword arguments. It can be sync or async. The handler sends the return value back to the model as a string.
- **The loop is bounded.** The handler packages stop after 10 tool steps and raise an error (the Claude, OpenAI, and LangChain messages handlers say `Tool loop exceeded the maximum number of steps (10)`). A runaway loop is almost always a prompt or schema bug.

To share tools across call sites, put them in a `Registry` (`Registry(handlers=..., tools=...)` in Python, `new Registry({ handlers, tools })` in Node.js) and pass `registry=` instead. A call receives only the tools its variation names. Some providers have built-in tools, such as `ClaudeWebSearch` from `launchdarkly-ai-claude-agents`. Assign one as the value for a tool key instead of a function, and its calls are tracked the same way.

### Custom handlers

Only write provider-specific tool code when no handler package covers your provider. Then build a handler with `create_handler()` / `createHandler()`. The SDK calls your function with five arguments: the resolved config, the user input, the tool functions, the variables, and the conversation history. The config is a plain dict: `config["model"]` holds `name` and `parameters`, and `config["tools"]` maps each tool key to `{type, name, description, parameters}`. Convert those to the provider's shape:

| Provider | Target shape | Where it goes on the call |
|---|---|---|
| OpenAI Chat Completions | `{type: "function", function: {name, description, parameters}}` | top-level `tools=[...]` |
| OpenAI Responses API | `{type: "function", name, description, parameters}` | top-level `tools=[...]` |
| Anthropic | `{name, description, input_schema}`, renaming `parameters` to `input_schema` | top-level `tools=[...]` |
| Bedrock Converse | `{toolSpec: {name, description, inputSchema: {json: parameters}}}` | inside `toolConfig.tools=[...]` |
| Gemini (`google-genai`) | `{function_declarations: [{name, description, parameters}]}` (Python) / `{functionDeclarations: [...]}` (Node) | `GenerateContentConfig.tools=[...]` |

The tool functions the SDK passes in are already wrapped to record `$ld:ai:tool_call`, so call them directly. Return the final text and the token usage. Here's a bounded loop against Anthropic:

```python
from anthropic import AsyncAnthropic
from launchdarkly_ai_server import (
    compose_history, create_handler, is_function_tool, parse_template, tool_result_string,
)

anthropic_client = AsyncAnthropic()
MAX_STEPS = 5
ANTHROPIC_PARAMS = {"max_tokens", "stop_sequences", "tool_choice", "thinking"}

class ToolLoopLimitError(Exception):
    pass

async def call_anthropic(ld_config, user_input, tool_handlers, variables, history):
    # Name each tool by its config key, which is also its key in tool_handlers. Offer only tools
    # with a function, as the handler packages do; native tools and unmatched keys are skipped.
    tools = [
        {"name": key, "description": t.get("description", ""), "input_schema": t["parameters"]}
        for key, t in (ld_config.get("tools") or {}).items()
        if is_function_tool(tool_handlers.get(key), key)
    ]
    # Handler packages fill {{name}} placeholders; custom handlers must do it themselves
    rendered = [{**m, "content": parse_template(m["content"], variables)} for m in ld_config.get("messages") or []]
    system = "\n".join(m["content"] for m in rendered if m["role"] == "system")
    # Agent-mode and UI-created variations often use instructions instead of a system message
    system = system or parse_template(ld_config.get("instructions") or "", variables)
    # Allowlist, not denylist: any other key on the variation (OpenAI-shaped fields, app knobs)
    # makes messages.create fail, and tools come from ld_config["tools"]. anthropic 2.x's API
    # rejects temperature, top_p, and top_k anywhere in the request, so this handler drops them;
    # remove them from the variation.
    params = {
        k: v for k, v in (ld_config["model"].get("parameters") or {}).items()
        if k in ANTHROPIC_PARAMS
    }
    max_tokens = params.pop("max_tokens", 1024)
    # Config turns (few-shot examples), then history, then the new input
    messages = compose_history(
        history=history or [],
        user_input=user_input,
        config_messages=[m for m in rendered if m["role"] != "system"],
    )
    usage = {"input": 0, "output": 0}
    for _ in range(MAX_STEPS):
        response = await anthropic_client.messages.create(
            model=ld_config["model"]["name"], max_tokens=max_tokens,
            system=system, messages=messages, tools=tools, **params,
        )
        usage["input"] += response.usage.input_tokens
        usage["output"] += response.usage.output_tokens
        if response.stop_reason != "tool_use":
            break
        messages.append({"role": "assistant", "content": response.content})
        results = []
        for block in response.content:
            if block.type == "tool_use":
                output = await tool_handlers[block.name](block.input)
                results.append({"type": "tool_result", "tool_use_id": block.id, "content": tool_result_string(output)})
        messages.append({"role": "user", "content": results})
    else:
        # Not RuntimeError: the app's fallback treats that as LaunchDarkly being unavailable
        raise ToolLoopLimitError(f"model still requesting tools after {MAX_STEPS} steps")
    text = "".join(b.text for b in response.content if b.type == "text")
    return {"output": text, "usage": usage}

anthropic_handler = create_handler(("Anthropic", "messages"), call_anthropic)
```

## Orchestrator Note

LangGraph, CrewAI, and AutoGen often generate schemas from function definitions. You still need to create tools in LaunchDarkly and attach keys to variations so the SDK knows what's available.

## Edge Cases

| Situation | Action |
|-----------|--------|
| Tool already exists (409) | Use existing or create with different key |
| Schema invalid | Use raw JSON Schema format (type: object, properties, required) |
| Wrong endpoint assumed | The tools use `/ai-tools`, not `/ai-configs/tools` |

## What NOT to Do

- Don't try to attach tools during config creation -- update the variation afterward
- Don't skip clear tool descriptions (LLM needs them to decide when to call)
- Don't forget to verify attachment after updating the variation
- Don't bundle `instructions`, `messages`, `model`, or `parameters` into the tool-attachment PATCH. Send `tools` alone unless the user explicitly asked for a multi-field update — bundled PATCHes silently clobber UI edits to the other fields.

## Related Skills

- `configs-create` -- Create config before attaching tools
- `configs-variations` -- Manage variations with different tool sets
