# AI Agent Tool Selection Optimizer - MCP Routing & Cost Audit (`quanmatrix/ai-agent-tool-selection-optimizer`) Actor

Analyze observed MCP and AI-agent tool telemetry to rank tools, expose reliability and cost risks, preserve task coverage, and generate an evidence-based routing policy.

- **URL**: https://apify.com/quanmatrix/ai-agent-tool-selection-optimizer.md
- **Developed by:** [Rafael Barreto Haddad](https://apify.com/quanmatrix) (community)
- **Categories:** Developer tools
- **Stats:** 2 total users, 1 monthly users, 100.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

from $17.50 / 1,000 results

This Actor is paid per event. You are not charged for the Apify platform usage, but only a fixed price for specific events.
Since this Actor supports Apify Store discounts, the price gets lower the higher subscription plan you have.

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

## What's an Apify Actor?

Actors are web data automations that power AI and operations. They run on the Apify platform to scrape websites, process data, connect APIs, and automate workflows.
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.
Actors are written with capital "A".

## 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.
The best way to integrate Actors is as follows.

- **AI agents and MCP clients** — the [Apify MCP server](https://docs.apify.com/integrations/mcp.md) at `https://mcp.apify.com` (remote, streamable HTTP, OAuth on first use).
- **Agentic workflows and local Actor development** — [Agent Skills](https://apify.com/.well-known/agent-skills/index.json) with the [Apify CLI](https://docs.apify.com/cli/docs.md): `npm install -g apify-cli`, then `apify login`.
- **JavaScript/TypeScript projects** — the official [JS/TS client](https://docs.apify.com/api/client/js/docs.md): `npm install apify-client`.
- **Python projects** — the official [Python client](https://docs.apify.com/api/client/python/docs.md): `pip install apify-client`.
- **Any other language** — the [REST API](https://docs.apify.com/api/v2.md).

For usage examples, see the [API](#api) section below.

For more details, see Apify documentation as [Markdown index](https://docs.apify.com/llms.txt) and [Markdown full-text](https://docs.apify.com/llms-full.txt).

# README

## AI Agent Tool Selection Optimizer

Runtime evidence for smaller, cheaper, more reliable MCP and AI-agent toolsets.

This Actor analyzes **observed tool usage telemetry**, not just tool names or descriptions. It combines call volume, reliability, latency, cost, and declared task coverage to rank tools, identify prune candidates, preserve unique capabilities, and generate a deterministic routing policy.

### Use cases

- MCP servers exposing many tools to an agent
- agent platforms with repeated wrong-tool calls
- AI FinOps teams reducing tool/API spend
- engineering teams comparing overlapping functions or connectors
- CI or weekly governance of production agent toolsets
- teams trying to reduce tool-schema/context overhead without blindly deleting capabilities

### Why use this Actor

Static tool-catalog pruning can tell you which tools *look* similar. This Actor works from what your production or test agents actually did. It can use:

- observed call counts
- successful or failed calls
- average and p95 latency
- average cost per call
- task types served by each tool
- an optional estimate of context tokens consumed per exposed tool

### Key features

- Runtime scoring from usage, reliability, latency, and cost telemetry
- Task-aware routing policy that preserves unique capabilities
- Explicit KEEP, BENCHMARK, and PRUNE\_CANDIDATE recommendations
- Deterministic analysis with no external LLM or paid API dependency

The output preserves the best observed tool for each declared task type even when the requested toolset cap is smaller. That reduces the risk of optimizing cost by accidentally removing a unique capability.

No external LLM or paid API is used. Analysis is deterministic and low-compute.

### Input

`tool_usage_logs` is required. Each row needs `tool_id` and `usage_count`. Add the optional telemetry fields you have; richer telemetry increases the usefulness of the recommendation.

### Example

```json
{
  "tool_usage_logs": [
    {
      "tool_id": "internal_docs_search",
      "usage_count": 1200,
      "success_count": 1176,
      "avg_latency_ms": 180,
      "p95_latency_ms": 360,
      "avg_cost_usd": 0.0015,
      "task_types": ["knowledge_search"]
    },
    {
      "tool_id": "web_search",
      "usage_count": 420,
      "success_count": 382,
      "avg_latency_ms": 820,
      "p95_latency_ms": 1450,
      "avg_cost_usd": 0.009,
      "task_types": ["knowledge_search", "current_web_research"]
    }
  ],
  "optimization_mode": "balanced",
  "max_recommended_tools": 12,
  "context_tokens_per_tool": 180
}
```

#### Optimization modes

- `balanced` — reliability, cost, latency, and observed usage
- `cost` — emphasize cheaper successful calls
- `reliability` — emphasize successful calls
- `latency` — emphasize faster tools
- `compact` — emphasize a smaller high-usage set while preserving task coverage

### Output

A run emits **one default-dataset item** containing the complete audit:

- ranked recommendations for every analyzed tool
- `KEEP`, `BENCHMARK`, or `PRUNE_CANDIDATE` action
- utility score and observed telemetry
- task-specific preferred-tool routing policy
- reliability risk list
- observed spend attributable to prune candidates
- potential tool-context reduction
- evidence confidence level

The same result is also written to the `OUTPUT` key-value-store record.

### Limitations

#### Interpreting prune candidates

A prune candidate is not an instruction to remove a production capability immediately. It means the observed telemetry does not justify keeping that tool in the default exposed set relative to the alternatives and declared task coverage. Replay representative tasks before removing or disabling it.

### Data provenance and privacy

The Actor uses only telemetry supplied in the Actor input. It does not contact external model providers, MCP servers, websites, or paid APIs. Do not submit secrets or raw user content when aggregated operational metrics are sufficient.

### Pricing

One successfully emitted audit equals one billable default-dataset item. The factory profit guard validates real Apify run cost before initial Store pricing is activated.

### Search terms

AI agent tool selection, MCP tool optimization, MCP routing audit, AI agent FinOps, reduce wrong tool calls, tool reliability benchmark, agent tool cost optimization, MCP context reduction, agent routing policy.

### Commercial intelligence layer

The Gen2 analysis can compare against a previous audit, translate tool pruning and context reduction into projected monthly and annual savings, produce a numeric confidence score, and return an explicit **GO / WARN / BLOCK** decision. Existing runtime ranking and routing fields remain unchanged for backward compatibility.

# Actor input Schema

## `tool_usage_logs` (type: `array`):

Aggregated runtime telemetry. More fields produce stronger recommendations.

## `optimization_mode` (type: `string`):

Choose whether recommendations prioritize balanced utility, cost, reliability, latency, or a compact toolset.

## `max_recommended_tools` (type: `integer`):

Upper bound for the default recommended active toolset before preserving unique task coverage.

## `min_usage_count` (type: `integer`):

Ignore tools with fewer observed calls than this threshold.

## `context_tokens_per_tool` (type: `integer`):

Optional estimate used only to quantify potential context reduction.

## `previous_analysis` (type: `object`):

Optional prior output from this Actor for temporal comparison.

## `monthly_call_volume` (type: `integer`):

Optional projected monthly tool calls for savings estimates. Zero uses the observed sample volume.

## `context_token_cost_per_million_usd` (type: `number`):

Optional effective context-token cost used to monetize context reduction.

## Actor input object example

```json
{
  "tool_usage_logs": [
    {
      "tool_id": "docs_search",
      "usage_count": 120,
      "success_count": 116,
      "avg_latency_ms": 180,
      "p95_latency_ms": 320,
      "avg_cost_usd": 0.0012,
      "task_types": [
        "knowledge_search"
      ]
    },
    {
      "tool_id": "web_search",
      "usage_count": 40,
      "success_count": 34,
      "avg_latency_ms": 850,
      "p95_latency_ms": 1400,
      "avg_cost_usd": 0.008,
      "task_types": [
        "knowledge_search",
        "current_web_research"
      ]
    }
  ],
  "optimization_mode": "balanced",
  "max_recommended_tools": 12,
  "min_usage_count": 1,
  "context_tokens_per_tool": 0,
  "previous_analysis": {},
  "monthly_call_volume": 0,
  "context_token_cost_per_million_usd": 0
}
```

# Actor output Schema

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

Runtime evidence, routing recommendations, reliability risks and prune candidates.

# 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 = {
    "tool_usage_logs": [
        {
            "tool_id": "docs_search",
            "usage_count": 120,
            "success_count": 116,
            "avg_latency_ms": 180,
            "p95_latency_ms": 320,
            "avg_cost_usd": 0.0012,
            "task_types": [
                "knowledge_search"
            ]
        },
        {
            "tool_id": "web_search",
            "usage_count": 40,
            "success_count": 34,
            "avg_latency_ms": 850,
            "p95_latency_ms": 1400,
            "avg_cost_usd": 0.008,
            "task_types": [
                "knowledge_search",
                "current_web_research"
            ]
        }
    ]
};

// Run the Actor and wait for it to finish
const run = await client.actor("quanmatrix/ai-agent-tool-selection-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 = { "tool_usage_logs": [
        {
            "tool_id": "docs_search",
            "usage_count": 120,
            "success_count": 116,
            "avg_latency_ms": 180,
            "p95_latency_ms": 320,
            "avg_cost_usd": 0.0012,
            "task_types": ["knowledge_search"],
        },
        {
            "tool_id": "web_search",
            "usage_count": 40,
            "success_count": 34,
            "avg_latency_ms": 850,
            "p95_latency_ms": 1400,
            "avg_cost_usd": 0.008,
            "task_types": [
                "knowledge_search",
                "current_web_research",
            ],
        },
    ] }

# Run the Actor and wait for it to finish
run = client.actor("quanmatrix/ai-agent-tool-selection-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 '{
  "tool_usage_logs": [
    {
      "tool_id": "docs_search",
      "usage_count": 120,
      "success_count": 116,
      "avg_latency_ms": 180,
      "p95_latency_ms": 320,
      "avg_cost_usd": 0.0012,
      "task_types": [
        "knowledge_search"
      ]
    },
    {
      "tool_id": "web_search",
      "usage_count": 40,
      "success_count": 34,
      "avg_latency_ms": 850,
      "p95_latency_ms": 1400,
      "avg_cost_usd": 0.008,
      "task_types": [
        "knowledge_search",
        "current_web_research"
      ]
    }
  ]
}' |
apify call quanmatrix/ai-agent-tool-selection-optimizer --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,quanmatrix/ai-agent-tool-selection-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/OLSHvUU9BnKFweMnJ/builds/JR8EXdetQnct1m7P7/openapi.json
