# Dynamic Tool Token Optimizer (`flowlockautomation/tool-token-optimizer`) Actor

Save up to 90% on input token costs with Just-In-Time progressive tool schema disclosure for Claude, Cursor, and autonomous AI agents.

- **URL**: https://apify.com/flowlockautomation/tool-token-optimizer.md
- **Developed by:** [Martin B.](https://apify.com/flowlockautomation) (community)
- **Stats:** 1 total users, 0 monthly users, 0.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

from $2.00 / 1,000 tool catalog compresseds

This Actor is paid per event. You are not charged for the Apify platform usage, but only a fixed price for specific events.

Learn more: https://docs.apify.com/actors/running/actors-in-store.md#pay-per-event

## What's an Apify Actor?

An Actor is a serverless cloud program that runs on the Apify platform. It has two run modes.
In Batch mode, an Actor accepts a well-defined JSON input, performs an action which can take anything from a few seconds to a few hours,
and optionally produces a well-defined JSON output, datasets with results, or files in key-value store.
In Standby mode, an Actor provides a web server which can be used as a website, API, or an MCP server.

Apify vocabulary and the platform model are defined once, in the agent quickstart at https://apify.com/agents.md.

## How to integrate an Actor?

If asked about integration, you help developers integrate Actors into their projects.
You adapt to their stack and deliver integrations that are safe, well-documented, and production-ready.

Do not guess an integration path. Every one of them is in the agent quickstart at https://apify.com/agents.md: the Apify MCP server, Agent Skills with the Apify CLI, the JavaScript and Python clients, the REST API, and the account-free path for an agent with no human to sign in. It also carries the rule on stating cost before the first paid run.

For examples already wired to this Actor's own input schema, see the [API](#api) section below.

Each client library has reference documentation the quickstart does not restate: [JavaScript/TypeScript](https://docs.apify.com/api/client/js/docs.md) (`npm install apify-client`) and [Python](https://docs.apify.com/api/client/python/docs.md) (`pip install apify-client`).

# README

## Tool Token Optimizer

Tool Token Optimizer is an Apify Actor for reducing the tool-schema context sent to LLMs and agent runtimes. It turns a large tool catalog into a compact discovery menu, then returns the full schema for a selected tool only when the caller needs it.

This progressive-disclosure pattern is intended for tool-using systems such as Cursor workflows, Claude Desktop integrations, and autonomous RAG or orchestration frameworks. The Actor processes the schema payload supplied with each run; callers retain the catalog and submit it again when requesting a schema.

### Operating Modes

#### `COMPRESS`: Build the Short Menu

Submit the raw tool array with `mode` set to `COMPRESS` (the default). The Actor strips parameter metadata from each menu entry and returns:

- `name`: the tool name, or `unnamed_tool` when omitted
- `description`: the description, or an empty string when omitted
- `hasParameters`: whether the input contained `inputSchema` or `parameters`
- `progressiveDisclosure`: always `true`

The response also includes the input `toolCount`. The compressed menu is intended for broad tool discovery; it does not contain the parameter schemas needed to execute a tool.

#### `INJECT`: Just-In-Time Schema Injection

Set `mode` to `INJECT`, provide the same catalog in `schemaPayload`, and set `targetTool` to the exact, case-sensitive tool name to retrieve. The Actor returns only that tool's schema under `schema`, using `inputSchema` first and `parameters` as a fallback.

If there is no matching tool, the Actor returns `found: false` and an empty schema. A missing or blank `targetTool` fails the run. The mode value itself is case-insensitive.

### Input and Output

Each tool in `schemaPayload` is a JSON object. A catalog can contain either `inputSchema` or `parameters` for its full parameter definition.

#### Example: Raw Catalog Input

```json
{
  "mode": "COMPRESS",
  "schemaPayload": [
    {
      "name": "search_documents",
      "description": "Search the indexed knowledge base for relevant documents.",
      "inputSchema": {
        "type": "object",
        "properties": {
          "query": {
            "type": "string",
            "description": "Natural-language search query"
          },
          "limit": {
            "type": "integer",
            "description": "Maximum results to return",
            "default": 10
          }
        },
        "required": ["query"]
      }
    },
    {
      "name": "get_document",
      "description": "Fetch a document by its identifier.",
      "parameters": {
        "type": "object",
        "properties": {
          "document_id": { "type": "string" }
        },
        "required": ["document_id"]
      }
    }
  ]
}
```

#### Example: Minimized Short Menu Output

For the input above, `COMPRESS` pushes and stores this result:

```json
{
  "mode": "COMPRESS",
  "toolCount": 2,
  "optimizedMenu": [
    {
      "name": "search_documents",
      "description": "Search the indexed knowledge base for relevant documents.",
      "hasParameters": true,
      "progressiveDisclosure": true
    },
    {
      "name": "get_document",
      "description": "Fetch a document by its identifier.",
      "hasParameters": true,
      "progressiveDisclosure": true
    }
  ]
}
```

#### Example: Inject One Schema

To retrieve `search_documents`, submit the original catalog with this input:

```json
{
  "mode": "INJECT",
  "targetTool": "search_documents",
  "schemaPayload": [
    {
      "name": "search_documents",
      "description": "Search the indexed knowledge base for relevant documents.",
      "inputSchema": {
        "type": "object",
        "properties": {
          "query": { "type": "string" },
          "limit": { "type": "integer", "default": 10 }
        },
        "required": ["query"]
      }
    }
  ]
}
```

The returned dataset item and `OUTPUT` key contain:

```json
{
  "mode": "INJECT",
  "targetTool": "search_documents",
  "found": true,
  "schema": {
    "type": "object",
    "properties": {
      "query": { "type": "string" },
      "limit": { "type": "integer", "default": 10 }
    },
    "required": ["query"]
  }
}
```

### Remote Integration

Keep Apify API tokens on a trusted server. Do not put a token in browser or mobile-app code, public source, or a customer-visible UI. For a customer-facing UI, have your backend call the Actor and keep its token in a server environment variable or secret store. Customers who call the Actor directly must use their own Apify token and have the required Actor access.

Actor run inputs and dataset outputs may be visible to users who have access to those runs or datasets. Do not submit sensitive schemas or data unless the Actor's access and data-retention settings are appropriate for them.

#### cURL

Run the Actor synchronously and receive its dataset items as JSON. Replace the Actor identifier and token with your own. Send either mode's input as the request body.

```bash
curl -X POST \
  "https://api.apify.com/v2/acts/YOUR_USERNAME~tool-token-optimizer/run-sync-get-dataset-items" \
  -H "Authorization: Bearer YOUR_APIFY_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "mode": "COMPRESS",
    "schemaPayload": [
      {
        "name": "search_documents",
        "description": "Search the indexed knowledge base.",
        "inputSchema": {
          "type": "object",
          "properties": { "query": { "type": "string" } },
          "required": ["query"]
        }
      }
    ]
  }'
```

For just-in-time retrieval, use the same endpoint with `mode: "INJECT"`, the `targetTool` name, and the catalog in `schemaPayload`. The endpoint returns dataset items; the Actor also writes the same result to the `OUTPUT` key-value store record.

#### Python Client

Install the Apify client in your trusted backend with `pip install apify-client`. Set `APIFY_TOKEN` in that server's environment or secret store, then call the deployed Actor. Do not bundle this code or token in a customer-facing frontend.

```python
import os

from apify_client import ApifyClient

client = ApifyClient(os.environ["APIFY_TOKEN"])

run = client.actor("YOUR_USERNAME/tool-token-optimizer").call(
    run_input={
        "mode": "INJECT",
        "targetTool": "search_documents",
        "schemaPayload": [
            {
                "name": "search_documents",
                "description": "Search the indexed knowledge base.",
                "inputSchema": {
                    "type": "object",
                    "properties": {"query": {"type": "string"}},
                    "required": ["query"],
                },
            }
        ],
    }
)

items = client.dataset(run["defaultDatasetId"]).list_items().items
print(items[0])
```

### Actor Outputs and Billing

Each successful operation writes its result to the `OUTPUT` key-value store record and pushes the same object as a dataset item. The Actor charges the `schema_compressed` event for each `COMPRESS` run and `schema_injected` only when an `INJECT` target is found. A not-found injection still returns a result but does not charge that event.

### Runtime

The Actor runs on the Apify Python Actor runtime. Its dependencies are declared in `requirements.txt`; deploy it through the Apify platform or the Apify CLI, then call it using the deployed Actor ID or username/name identifier.

# Actor input Schema

## `mode` (type: `string`):

Choose whether to compress the schema or retrieve one tool's full parameters.

## `targetTool` (type: `string`):

Tool name whose full parameters should be retrieved in INJECT mode.

## `schemaPayload` (type: `array`):

Tool schemas to compress or search.

## Actor input object example

```json
{
  "mode": "COMPRESS"
}
```

# Actor output Schema

## `results` (type: `string`):

Output records for the completed operation.

# API

You can run this Actor programmatically using our API. Below are code examples in JavaScript, Python, and CLI, as well as the OpenAPI specification and MCP server setup.

## JavaScript example

```javascript
import { ApifyClient } from 'apify-client';

// Initialize the ApifyClient with your Apify API token
// Replace the '<YOUR_API_TOKEN>' with your token
const client = new ApifyClient({
    token: '<YOUR_API_TOKEN>',
});

// Prepare Actor input
const input = {};

// Run the Actor and wait for it to finish
const run = await client.actor("flowlockautomation/tool-token-optimizer").call(input);

// Fetch and print Actor results from the run's dataset (if any)
console.log('Results from dataset');
console.log(`💾 Check your data here: https://console.apify.com/storage/datasets/${run.defaultDatasetId}`);
const { items } = await client.dataset(run.defaultDatasetId).listItems();
items.forEach((item) => {
    console.dir(item);
});

// 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/js/docs

```

## Python example

```python
from apify_client import ApifyClient

# Initialize the ApifyClient with your Apify API token
# Replace '<YOUR_API_TOKEN>' with your token.
client = ApifyClient("<YOUR_API_TOKEN>")

# Prepare the Actor input
run_input = {}

# Run the Actor and wait for it to finish
run = client.actor("flowlockautomation/tool-token-optimizer").call(run_input=run_input)

# Fetch and print Actor results from the run's dataset (if there are any)
print(f"💾 Check your data here: https://console.apify.com/storage/datasets/{run.default_dataset_id}")
for item in client.dataset(run.default_dataset_id).iterate_items():
    print(item)

# 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/python/docs/quick-start

```

## CLI example

```bash
echo '{}' |
apify call flowlockautomation/tool-token-optimizer --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,flowlockautomation/tool-token-optimizer"
        }
    }
}
```

The hosted server signs you in with OAuth on first connect, so no API token belongs in this config. Clients without OAuth support can send an `Authorization: Bearer <APIFY_API_TOKEN>` header instead, using a token from API & Integrations in Apify Console (https://console.apify.com/settings/integrations).

## OpenAPI specification

Download the OpenAPI definition: https://api.apify.com/v2/actors/GsgCmkHxv22pc5JMR/builds/SeGGTJMCFBlgA4Vau/openapi.json
