Contents · 11 sections↓
- 01What happens when an LLM agent has too many tools?
- 02How many tools is too many for an LLM?
- 03How does semantic tool selection work?
- 04What you need
- 05How to fix too many MCP tools, step by step
- 06What happens past 128 tools?
- 07Do follow-up messages keep their tools?
- 08The other fix: fewer, better tools
- 09Common mistakes with LLM tool selection
- 10Frequently asked questions
- 11Where to go next
Connect a couple of MCP servers to an agent and it can easily see 100 or more tools. Every one of them goes to the model on every call, as a name, a description and a JSON schema. Too many MCP tools cost tokens and time, push the request past provider limits, and give the model more look-alikes to pick from. This guide shows how to fix LLM tool selection in Python: send each model call only the tools that fit it, check offline that the right tool makes the cut, and tune the selection when it doesn't. You'll use Promptise Foundry's optimize_tools on a 122-tool admin server, and every step works the same on your own servers.
What happens when an LLM agent has too many tools?
Three things go wrong. Every model call carries every tool definition, so cost and latency grow with the tool count: the 122 tools in this guide take about 12,400 tokens before the model reads a word of the task. Past a limit the call fails: OpenAI rejects requests with more than 128 tools. And look-alike tools (suspend_user and delete_user, create_domain and create_dns_record) give the model more ways to pick the wrong one.
The fix is to send each model call only the tools that fit the request. With Promptise Foundry, that's one argument:
agent = await build_agent(
model="openai:gpt-5-mini",
servers={"platform": StdioServerSpec(command=sys.executable, args=["platform_server.py"])},
optimize_tools="semantic", # each request gets only the tools that fit it
)Before each model call, the agent compares the recent conversation with every tool description using a small local embedding model. It offers the model the 8 best matches, plus a request_more_tools fallback. Here is what the model sees for "dep_9f2c is building the wrong branch. Stop it." on the 122-tool server:
dep_9f2c is building the wrong branch. Stop it.
offered: ['create_project', 'delete_project', 'archive_project', 'transfer_project', 'cancel_deployment', 'redeploy', 'unset_environment_variable', 'update_organization_settings', 'request_more_tools']
called: ['cancel_deployment']
offered: ['delete_project', 'create_deployment', 'update_deployment', 'delete_deployment', 'archive_project', 'rollback_deployment', 'cancel_deployment', 'redeploy', 'request_more_tools']
called: nothing, it answered
answer: Done — I stopped deployment dep_9f2c.Nine tools instead of 122. The catch is that the right tool has to be among the nine. The rest of this guide shows how selection works, how to check it before it costs you anything, and how to tune it.
[02]
How many tools is too many for an LLM?
There is no single number, but the published guidance lines up. Under about 20 tools per request is comfortable. Around 30 to 50, tool choice starts to slip. On OpenAI, 128 is a hard limit. Treat these as warning lines, not rules:
Source | What it says |
|---|---|
"Aim for fewer than 20 functions available at the start of a turn", as a soft suggestion. Use tool search for large tool sets | |
OpenAI API (the error under "What happens past 128 tools?" below) | A request with more than 128 tools is rejected: "Expected an array with maximum length 128" |
Claude's ability to pick the right tool degrades once you exceed 30 to 50 tools. Five common MCP servers can take about 55,000 tokens of definitions. Tool search is suggested from 10 tools or 10,000 tokens of definitions | |
RAG-MCP (Gan and Sun, 2025) | Retrieving the relevant tools first raised tool selection accuracy from 13.62% to 43.13% on their benchmark and cut prompt tokens by more than half |
Accuracy depends less on the raw count than on how alike the tools are. A capable model can pick well from 100 or more tools when each description says what the tool is for. Cost, latency and provider limits usually bite first. So the goal is the smallest set of tools that still contains the right one.
[03]
How does semantic tool selection work?
optimize_tools works in two layers. The static layer runs once, when the agent is built: it strips parameter descriptions from the schemas and shortens long tool descriptions. The semantic layer runs before every model call:
Rendering diagram…
There are three presets:
Preset | Parameter descriptions | Tool descriptions cut at | Nested schemas | Tools per model call |
|---|---|---|---|---|
"minimal" (also True) | Removed | 200 characters | Kept | All |
"standard" | Removed, nested ones too | 150 characters | Flattened beyond depth 3 | All |
"semantic" | Removed, nested ones too | 100 characters | Flattened beyond depth 2 | 8, plus preserved tools and request_more_tools |
Four details decide how well it works:
The index embeds
name: descriptionafter shortening. With the semantic preset, a request is matched against the first 100 characters of each description.The query is the recent conversation. It is built from the latest user message, the assistant reply it answers, the tool calls of the turn and up to three earlier user turns (semantic_context_turns). Tools already called in the turn stay on offer.
The model can ask for more. request_more_tools takes a query or exact tool_names, and the tools it returns are offered from the next model call on.
Selection is not access control. It decides what the model is shown. A call to a tool that exists but wasn't offered still runs, so guard risky tools with approval or server-side checks.
[04]
What you need
Python 3.10 or newer.
Promptise Foundry with the tool-optimization extra, which brings sentence-transformers for the embeddings. It pulls in PyTorch, so expect a large download. Without it, build_agent(optimize_tools="semantic") raises an ImportError that names the extra.
An OpenAI API key. The default embedding model, all-MiniLM-L6-v2, runs locally. Promptise downloads it from Hugging Face on first use and caches it in ~/.cache/huggingface/.
pip install "promptise[tool-optimization]"
export OPENAI_API_KEY="sk-..."[05]
How to fix too many MCP tools, step by step
Build a server with many tools, or use your own
To see the problem, you need a server that looks like a real admin API: many resources, the usual list, get, create, update and delete for each, and the special actions every API grows. This helper generates them from tables. Each tool echoes its arguments back, which is all you need to see which one the model picked:
"""Generate many MCP tools from tables. Every tool echoes its arguments back."""
import inspect
from typing import Annotated
from pydantic import Field
def make_tool(server, name: str, description: str, params: dict[str, str]):
"""Register one tool. Parameters whose description starts with "Optional" may be left out."""
async def handler(**kwargs):
return {"ok": True, "tool": name, "arguments": kwargs}
parameters, annotations = [], {}
for p, d in params.items():
optional = d.startswith("Optional")
annotation = Annotated[str | None if optional else str, Field(description=d)]
parameters.append(inspect.Parameter(p, inspect.Parameter.KEYWORD_ONLY, annotation=annotation,
default=None if optional else inspect.Parameter.empty))
annotations[p] = annotation
handler.__signature__ = inspect.Signature(parameters)
handler.__annotations__ = annotations
handler.__name__ = name
server.tool(name=name, description=description)(handler)
def add_tools(server, resources: dict, actions: dict):
"""Five standard tools per resource, plus one tool per action."""
for res, (plural, example, what, fields) in resources.items():
noun = res.replace("_", " ")
id_param = {f"{res}_id": f'The {noun} ID, for example "{example}".'}
make_tool(server, f"list_{res}s",
f"List {plural} in the organization, newest first. A {noun} is {what}. "
f"Returns IDs you can pass to get_{res}.",
{"filter": "Optional text to filter by.", "limit": "Optional maximum number of results."})
make_tool(server, f"get_{res}", f"Get one {noun} by ID, with all its fields.", id_param)
make_tool(server, f"create_{res}", f"Create a {noun}.", dict(fields))
make_tool(server, f"update_{res}", f"Change fields of an existing {noun}.",
{**id_param, **{k: "Optional " + v for k, v in fields.items()}})
make_tool(server, f"delete_{res}", f"Delete a {noun} permanently. This cannot be undone.", id_param)
for name, (description, params) in actions.items():
make_tool(server, name, description, params)The server file is mostly data, one add_tools call per area. Write the descriptions the way a careful API team would, including when to use a tool rather than its look-alike. Here is the start of the file, with the first area:
"""Acme platform admin API: 14 resources x 5 standard tools + 52 actions = 122 tools.
Each add_tools call registers one area: list, get, create, update and delete for every
resource, plus the actions beyond those. Run it over stdio: python platform_server.py
"""
from promptise.mcp.server import MCPServer
from acme_tools import add_tools
server = MCPServer("acme-platform")
# resources: {name: (plural, ID example, what it is, {field: description})}
# actions: {name: (description, {parameter: description})}
# Users and teams
add_tools(server, resources={
"user": ("users", "u_42", "a person with a login in your organization",
{"email": "Work email address.", "role": "One of owner, admin, member, billing or viewer."}),
"team": ("teams", "t_7", "a group of users that share access to projects",
{"name": "Display name of the team.", "description": "What the team works on."}),
}, actions={
"invite_user": ("Send someone an email invitation to join the organization with a role. "
"Use this, not create_user, for people who don't have an account yet.",
{"email": "Email address to invite.", "role": "Role to grant when they accept."}),
"suspend_user": ("Suspend a user so they can't sign in. Their data and memberships are kept and can be restored. "
"Use this, not delete_user, when someone leaves the company.",
{"user_id": "The user to suspend.", "reason": "Why, recorded in the audit log."}),
"reactivate_user": ("Lift a suspension so the user can sign in again, with their old memberships.",
{"user_id": "The suspended user."}),
"revoke_user_sessions": ("Sign a user out everywhere by ending all their active sessions and tokens. "
"They can sign in again; use it when a device is lost or an account may be compromised.",
{"user_id": "The user to sign out."}),
"reset_user_mfa": ("Remove a user's two-factor devices so they can enroll a new one, for example after losing a phone.",
{"user_id": "The user whose devices to remove."}),
"enforce_mfa": ("Require two-factor authentication for every member of the organization.",
{"grace_days": "Optional days members have to enroll before they are locked out."}),
"transfer_ownership": ("Make another admin the owner of the organization. The current owner becomes an admin.",
{"user_id": "The new owner."}),
"add_team_member": ("Add an existing user to a team, giving them the team's project access.",
{"team_id": "The team.", "user_id": "The user to add."}),
"remove_team_member": ("Remove a user from a team. They keep their account and other teams.",
{"team_id": "The team.", "user_id": "The user to remove."}),
})The full server repeats this for nine more areas: projects and deployments, domains, API keys, webhooks, feature flags, buckets, databases, alerts and incidents, and the organization itself. That makes 14 resources and 52 actions, 122 tools in all. It ends by starting the server over stdio:
if __name__ == "__main__":
server.run()If you already have MCP servers with many tools, skip this step. Every script below takes a SERVERS mapping; point it at yours.
Measure what the model receives
Before you spend anything on model calls, look at the payload. This script builds an agent at each level and counts the tokens of the tool definitions, serialized the way LangChain sends them to OpenAI. No model is called:
"""How big are the tool definitions the model receives, at each optimization level?
An offline estimate with tiktoken, which langchain-openai brings; no model is called.
python definitions.py
"""
import asyncio
import json
import sys
import tiktoken
from langchain_core.utils.function_calling import convert_to_openai_tool
from promptise import build_agent
from promptise.config import StdioServerSpec
SERVERS = {"platform": StdioServerSpec(command=sys.executable, args=["platform_server.py"])}
enc = tiktoken.get_encoding("o200k_base")
def definition_tokens(tools) -> int:
payload = [convert_to_openai_tool(t) for t in tools]
return len(enc.encode(json.dumps(payload)))
async def main():
for level in [None, "minimal", "standard", "semantic"]:
agent = await build_agent(model="openai:gpt-5-mini", servers=SERVERS, optimize_tools=level)
try:
tools = agent.tools
suspend = next(t for t in tools if t.name == "suspend_user")
print(f"--- optimize_tools={level!r}: {len(tools)} tools, {definition_tokens(tools)} tokens")
print(json.dumps(convert_to_openai_tool(suspend)["function"]))
finally:
await agent.shutdown()
asyncio.run(main())--- optimize_tools=None: 122 tools, 12432 tokens
{"name": "suspend_user", "description": "Suspend a user so they can't sign in. Their data and memberships are kept and can be restored. Use this, not delete_user, when someone leaves the company.", "parameters": {"properties": {"user_id": {"description": "The user to suspend.", "type": "string"}, "reason": {"description": "Why, recorded in the audit log.", "type": "string"}}, "required": ["user_id", "reason"], "type": "object"}}
--- optimize_tools='minimal': 122 tools, 10022 tokens
{"name": "suspend_user", "description": "Suspend a user so they can't sign in. Their data and memberships are kept and can be restored. Use this, not delete_user, when someone leaves the company.", "parameters": {"properties": {"user_id": {"type": "string"}, "reason": {"type": "string"}}, "required": ["user_id", "reason"], "type": "object"}}
--- optimize_tools='standard': 122 tools, 9927 tokens
{"name": "suspend_user", "description": "Suspend a user so they can't sign in. Their data and memberships are kept and can be restored. Use this, not delete_user, when someone leaves the...", "parameters": {"properties": {"user_id": {"type": "string"}, "reason": {"type": "string"}}, "required": ["user_id", "reason"], "type": "object"}}
--- optimize_tools='semantic': 123 tools, 9931 tokens
{"name": "suspend_user", "description": "Suspend a user so they can't sign in. Their data and memberships are kept and can be restored.", "parameters": {"properties": {"user_id": {"type": "string"}, "reason": {"type": "string"}}, "required": ["user_id", "reason"], "type": "object"}}Watch what happens to suspend_user. minimal drops the parameter descriptions. standard cuts the description mid-sentence. semantic cuts it before the one sentence that says when to use it. The cut ends on a whole sentence when that keeps at least two thirds of the limit, which is why the semantic version stops cleanly after "restored."
The static presets save what your schemas spend on parameter descriptions, long descriptions and nesting. On this server, with flat schemas and short parameter descriptions, that is about a fifth. Servers with long, nested schemas save more. The semantic line counts all 123 tools (122 plus the fallback), but the model only sees 8 of them per call, plus the fallback.
Turn on semantic selection and watch what the model is offered
Next, run real requests and print, for every model call, the tools it was offered and the tools it called. A LangChain callback can read both: invocation_params holds the tools actually sent, so you see the ones chosen for that call, not the full list:
"""Watch semantic tool selection: the tools each model call is offered, and the ones it calls.
python watch_selection.py # the semantic preset
python watch_selection.py --tuned # whole descriptions, another embedding model
"""
import asyncio
import sys
from langchain_core.callbacks import AsyncCallbackHandler
from promptise import OptimizationLevel, ToolOptimizationConfig, build_agent
from promptise.config import StdioServerSpec
from promptise.engine import GraphIterationLimitError
SERVERS = {"platform": StdioServerSpec(command=sys.executable, args=["platform_server.py"])}
REQUESTS = [
"dep_9f2c is building the wrong branch. Stop it.",
"Somebody removed db_staging last week. Find out who.",
"Priya's laptop (u_51) was stolen. Log her out of everything right now; she still works here.",
]
TUNED = ToolOptimizationConfig(
level=OptimizationLevel.SEMANTIC,
max_description_length=400, # embed whole descriptions, not the first 100 characters
embedding_model="BAAI/bge-small-en-v1.5", # the model that did best in retrieval_check.py
)
class ShowToolChoice(AsyncCallbackHandler):
"""Prints, for every model call, the tools it was offered and the tools it called."""
async def on_chat_model_start(self, serialized, messages, **kwargs):
tools = (kwargs.get("invocation_params") or {}).get("tools") or []
print(" offered:", [t["function"]["name"] for t in tools])
async def on_llm_end(self, response, **kwargs):
message = response.generations[0][0].message
print(" called: ", [c["name"] for c in message.tool_calls] or "nothing, it answered")
async def main():
agent = await build_agent(
model="openai:gpt-5-mini",
servers=SERVERS,
optimize_tools=TUNED if "--tuned" in sys.argv else "semantic",
)
try:
for text in REQUESTS:
print(text)
try:
result = await agent.ainvoke(
{"messages": [{"role": "user", "content": text}]}, config={"callbacks": [ShowToolChoice()]}
)
print(" answer: ", " ".join(result["messages"][-1].content.split())[:220])
except GraphIterationLimitError as error:
# The model was still calling tools when the run reached max_agent_iterations.
print(" stopped at the iteration limit, results never read:", error.pending_tools)
finally:
await agent.shutdown()
asyncio.run(main())Run python watch_selection.py. The first request is the one you saw above: cancel_deployment was in the first 8 and the model used it. The other two show the two ways selection goes wrong.
The audit question is about deleting a database, word for word, so the first call got database tools and no audit log. The model asked request_more_tools for help and got list_audit_events on the next call:
Somebody removed db_staging last week. Find out who.
offered: ['delete_team', 'remove_team_member', 'delete_project', 'list_databases', 'create_database', 'update_database', 'delete_database', 'restore_database_backup', 'request_more_tools']
called: ['list_databases', 'request_more_tools']
offered: ['delete_project', 'delete_environment', 'get_deployment_logs', 'list_databases', 'create_database', 'delete_database', 'restore_database_backup', 'delete_incident', 'list_audit_events', 'export_audit_log', 'search_logs', 'get_usage_report', 'request_more_tools']
called: ['list_audit_events']
…
stopped at the iteration limit, results never read: ['list_audit_events']That's the fallback doing its job. The run still ended badly, for a reason that has nothing to do with selection: this echo server returns no audit events, so the model kept asking until the run reached its iteration limit (build_agent(max_agent_iterations=...), 25 by default). Promptise then raises GraphIterationLimitError with the tools whose results the model never read in pending_tools. Catch it where you call the agent, and make your tools say plainly when they found nothing.
The session revoke went wrong in a worse way. "Log her out of everything" means revoke_user_sessions, but the user tools around it ranked higher, and the right tool wasn't in the first 8:
Priya's laptop (u_51) was stolen. Log her out of everything right now; she still works here.
offered: ['delete_user', 'delete_team', 'suspend_user', 'reactivate_user', 'reset_user_mfa', 'transfer_ownership', 'delete_database', 'delete_incident', 'request_more_tools']
called: ['suspend_user', 'reset_user_mfa']
offered: ['delete_user', 'suspend_user', 'reactivate_user', 'revoke_user_sessions', 'reset_user_mfa', 'enforce_mfa', 'remove_team_member', 'delete_incident', 'request_more_tools']
called: nothing, it answered
answer: I've suspended Priya's account (u_51) and removed her enrolled MFA devices. This will prevent sign-in and require reactivation and MFA re-enrollment. If you want to allow her temporary access later, I can reactivate herThe model didn't ask for more tools. It used the closest ones it had, suspended a user who still works there and removed her MFA devices. The second call did offer revoke_user_sessions, because the selection reads the turn's tool calls, but by then the work was done. This is the failure to take seriously: with the right tool missing, a model often reaches for a heavier look-alike. Suspension can be undone; the same reflex with a destructive tool could not be.
Check retrieval offline before you pay for model calls
Every miss above can be found without calling the model. Write down the requests your users actually make, each with the one tool that does the job:
"""Requests phrased the way people ask, each with the one tool that does the job."""
TASKS = [
("Jane (u_42) left the company yesterday. Make sure she can't get in any more.", "suspend_user"),
("The last deploy of prj_web_shop broke checkout. Put production back the way it was.", "rollback_deployment"),
("Our CI key key_8812 leaked in a public repo. Give us a fresh secret for it with the same permissions.", "rotate_api_key"),
("Point www.acme.io at acme-shop.pages.dev with a CNAME.", "create_dns_record"),
("Somebody removed db_staging last week. Find out who.", "list_audit_events"),
("dep_9f2c is building the wrong branch. Stop it.", "cancel_deployment"),
("How much was key_8812 used this week?", "get_api_key_usage"),
("Bring back last night's backup of db_staging.", "restore_database_backup"),
("Add Omar (u_77) to the payments team, t_7.", "add_team_member"),
("inc_12 is fixed, the database is healthy again. Close it out.", "resolve_incident"),
("Turn new_checkout on for 10% of our users.", "set_feature_flag_rollout"),
("Priya's laptop (u_51) was stolen. Log her out of everything right now; she still works here.", "revoke_user_sessions"),
("Ship the preview build dep_7a1e to production as it is.", "promote_deployment"),
("db_staging keeps running out of memory. Put it on the large plan.", "resize_database"),
("Our endpoint was down on Tuesday and missed delivery dlv_501. Send it again.", "retry_webhook_delivery"),
("We need more than 20 projects. Can you get our limit raised to 50?", "request_quota_increase"),
("Sam (sam@acme.io) is joining finance. Get them into the org with the billing role.", "invite_user"),
("Is acme.io verified yet? We added the TXT record an hour ago.", "verify_domain"),
("ar_5 keeps paging everyone during the migration tonight. Shut it up for two hours.", "mute_alert_rule"),
("Set CHECKOUT_REGION to eu-west-1 on env_prod.", "set_environment_variable"),
]Then build the same index the agent uses, ToolIndex from promptise.tool_optimization, over the agent's own tools, and check each expected tool against the top 8. This script compares three setups: the preset, whole descriptions, and whole descriptions with a different embedding model:
"""Before you pay for a single model call: would semantic selection hand the model the right tool?
Builds the same index the agent builds (same tools, same truncated descriptions,
same embedding model) and checks each request's expected tool against the top 8.
python retrieval_check.py
"""
import asyncio
import sys
from promptise import OptimizationLevel, ToolOptimizationConfig, build_agent
from promptise.config import StdioServerSpec
from promptise.tool_optimization import ToolIndex
from tasks import TASKS
SERVERS = {"platform": StdioServerSpec(command=sys.executable, args=["platform_server.py"])}
SETUPS = {
"semantic preset": (ToolOptimizationConfig(level=OptimizationLevel.SEMANTIC), "all-MiniLM-L6-v2"),
"full descriptions": (ToolOptimizationConfig(level=OptimizationLevel.SEMANTIC, max_description_length=400),
"all-MiniLM-L6-v2"),
"full descriptions, bge-small": (ToolOptimizationConfig(level=OptimizationLevel.SEMANTIC, max_description_length=400),
"BAAI/bge-small-en-v1.5"),
}
async def main():
for label, (config, embedding_model) in SETUPS.items():
agent = await build_agent(model="openai:gpt-5-mini", servers=SERVERS, optimize_tools=config)
try:
tools = [t for t in agent.tools if t.name != "request_more_tools"]
index = ToolIndex(tools, model_name_or_path=embedding_model)
misses = []
for text, expected in TASKS:
names = [t.name for t in index.select(text, top_k=8)]
if expected not in names:
misses.append(f"{expected} (got {', '.join(names[:3])}, ...)")
print(f"{label}: right tool in the top 8 for {len(TASKS) - len(misses)}/{len(TASKS)} requests")
for miss in misses:
print(" missed", miss)
finally:
await agent.shutdown()
asyncio.run(main())semantic preset: right tool in the top 8 for 16/20 requests
missed suspend_user (got delete_team, list_incidents, reactivate_user, ...)
missed list_audit_events (got delete_database, create_database, restore_database_backup, ...)
missed revoke_user_sessions (got reset_user_mfa, reactivate_user, delete_user, ...)
missed mute_alert_rule (got resolve_incident, transfer_project, escalate_incident, ...)
full descriptions: right tool in the top 8 for 17/20 requests
missed list_audit_events (got delete_database, create_database, restore_database_backup, ...)
missed revoke_user_sessions (got suspend_user, reset_user_mfa, reactivate_user, ...)
missed mute_alert_rule (got resolve_incident, transfer_project, escalate_incident, ...)
full descriptions, bge-small: right tool in the top 8 for 19/20 requests
missed create_dns_record (got request_quota_increase, verify_domain, search_logs, ...)Read the misses, not just the score:
suspend_useris a truncation problem. "Jane left the company" doesn't look much like "Suspend a user so they can't sign in". The sentence that matches, "when someone leaves the company", sits after character 100. Whole descriptions fix it.list_audit_eventsis a topic problem. Embedding models match topics, not intent. A question about who deleted a database looks like the database tools.The embedding model matters, both ways. bge-small-en-v1.5 found the audit log, the session revoke and the alert rule, and lost the DNS record. A different model isn't automatically a better one.
The preset's misses include both requests that went wrong in Step 3. That's what makes this check worth running: it costs no model calls, and it shows which requests will start without the right tool.
Tune the selection
Work through these in order, and re-run the retrieval check after each change:
Keep whole descriptions in the index. ToolOptimizationConfig(level=OptimizationLevel.SEMANTIC, max_description_length=400) embeds the "when to use it" sentences the preset cuts. The definitions sent to the model stay small, because it still sees only 8 tools.
Put the "when to use it" first. The index reads name: description. A description that opens with the situations people describe ("someone left", "find out who changed something") matches requests better than one that opens with what the endpoint does.
Try another embedding model with embedding_model=, a Hugging Face name or a local path. Keep it only if your retrieval check improves.
Use
semantic_top_kandpreserve_tools. semantic_top_k sets how many tools each call gets. Don't set it too low: with only a few tools on offer, the model is more likely to take a near match than to ask for more. preserve_tools adds tools to every call on top of those, with their full descriptions and parameter descriptions.
The --tuned run of watch_selection.py uses whole descriptions and bge-small-en-v1.5, the setup that did best in the retrieval check. The audit log is now in the first call, and Priya is signed out instead of suspended:
Somebody removed db_staging last week. Find out who.
offered: ['remove_team_member', 'delete_deployment', 'cancel_deployment', 'update_database', 'delete_database', 'restore_database_backup', 'delete_incident', 'list_audit_events', 'request_more_tools']
called: ['list_audit_events']
…
Priya's laptop (u_51) was stolen. Log her out of everything right now; she still works here.
offered: ['suspend_user', 'reactivate_user', 'revoke_user_sessions', 'reset_user_mfa', 'remove_team_member', 'delete_database', 'acknowledge_incident', 'list_audit_events', 'request_more_tools']
called: ['revoke_user_sessions']
offered: ['delete_user', 'suspend_user', 'reactivate_user', 'revoke_user_sessions', 'reset_user_mfa', 'remove_team_member', 'delete_database', 'acknowledge_incident', 'request_more_tools']
called: nothing, it answered
answer: Done — Priya (u_51) has been signed out everywhere. Would you like me to also suspend her account, reset her MFA, or remove access to any specific teams or databases?Tuning fixes the requests you tested. It doesn't guarantee the next one, so keep approval on tools that change things, as covered in human-in-the-loop approval.
[06]
What happens past 128 tools?
Connect a second ordinary server and the total can cross OpenAI's limit. Here is a 26-tool billing and support server, built the same way as the platform server:
"""Acme billing and support API: 4 resources x 5 standard tools + 6 actions = 26 tools."""
from promptise.mcp.server import MCPServer
from acme_tools import add_tools
server = MCPServer("acme-customers")
add_tools(server, resources={
"customer": ("customers", "cus_310", "a company that pays for Acme",
{"name": "Company name.", "billing_email": "Where invoices go."}),
"subscription": ("subscriptions", "sub_77", "a customer's paid plan and its renewal date",
{"customer_id": "The customer.", "plan": "starter, team or business."}),
"invoice": ("invoices", "inv_2041", "a bill sent to a customer",
{"customer_id": "The customer.", "amount": "Amount in USD."}),
"ticket": ("support tickets", "tk_918", "a customer's support request",
{"customer_id": "The customer.", "subject": "Short subject line."}),
}, actions={
"refund_invoice": ("Refund all or part of a paid invoice to the customer's card.",
{"invoice_id": "The invoice.", "amount": "Optional amount; the full invoice by default."}),
"apply_coupon": ("Apply a discount coupon to a customer's subscription.",
{"subscription_id": "The subscription.", "coupon": "Coupon code."}),
"pause_subscription": ("Pause a subscription for up to three months. Nothing is billed while paused.",
{"subscription_id": "The subscription.", "months": "1, 2 or 3."}),
"cancel_subscription": ("Cancel a subscription at the end of the current billing period.",
{"subscription_id": "The subscription."}),
"add_ticket_note": ("Add an internal note to a support ticket. The customer doesn't see it.",
{"ticket_id": "The ticket.", "note": "Text of the note."}),
"escalate_ticket": ("Hand a support ticket to the engineering on-call queue.", {"ticket_id": "The ticket."}),
})
if __name__ == "__main__":
server.run()Together with the platform server's 122 tools, that makes 148. This script sends one request with all of them, then with semantic selection:
"""Two ordinary MCP servers, 148 tools together: past OpenAI's limit of 128 tools per request.
python two_servers.py
"""
import asyncio
import sys
from promptise import build_agent
from promptise.config import StdioServerSpec
SERVERS = {
"platform": StdioServerSpec(command=sys.executable, args=["platform_server.py"]),
"customers": StdioServerSpec(command=sys.executable, args=["customer_server.py"]),
}
REQUEST = "Add a note to ticket tk_918: the customer called back and the issue is solved."
async def main():
for level in [None, "semantic"]:
agent = await build_agent(model="openai:gpt-5-mini", servers=SERVERS, optimize_tools=level)
try:
result = await agent.ainvoke({"messages": [{"role": "user", "content": REQUEST}]})
print(f"optimize_tools={level!r}, {len(agent.tools)} tools:", result["messages"][-1].content)
except Exception as error:
print(f"optimize_tools={level!r}, {len(agent.tools)} tools: {type(error).__name__}: {error}")
finally:
await agent.shutdown()
asyncio.run(main())optimize_tools=None, 148 tools: GraphExecutionError: Graph 'react' failed at node 'reason': OpenAIInvalidRequestError: Error code: 400 - {'error': {'message': "Invalid 'tools': array too long. Expected an array with maximum length 128, but got an array with length 148 instead.", 'type': 'invalid_request_error', 'param': 'tools', 'code': 'array_above_max_length'}}
optimize_tools='semantic', 149 tools: Done — I added the internal note to ticket tk_918: "Customer called back and the issue is solved."With every tool sent, OpenAI refuses the first call. minimal and standard fail the same way, since they still send every tool. Semantic selection sends 8 tools plus the fallback and any preserved tools, so it stays far below the limit. Tools the model unlocks with request_more_tools are capped too: one call returns at most 32, and a model call gets at most 100 indexed tools.
[07]
Do follow-up messages keep their tools?
Usually, because the selection reads the conversation, not just the last message. It also reads what the assistant said, and that can pull it off course. followup.py asks for a rollback directly, then asks "What can we do? Don't change anything yet." and answers the reply with "Yes, go ahead.". It prints the tools each first model call was offered:
"""Semantic selection in a conversation: the tools offered for a direct request and for "Yes, go ahead."
Asks for a rollback directly, then has the same job confirmed as a follow-up to an assistant
reply, and prints the tools the first model call of each turn was offered.
python followup.py
"""
import asyncio
import sys
from langchain_core.callbacks import AsyncCallbackHandler
from promptise import build_agent
from promptise.config import StdioServerSpec
class FirstCallTools(AsyncCallbackHandler):
"""Remembers the tools offered to the first model call of a run."""
def __init__(self):
self.tools = None
async def on_chat_model_start(self, serialized, messages, **kwargs):
if self.tools is None:
tools = (kwargs.get("invocation_params") or {}).get("tools") or []
self.tools = [t["function"]["name"] for t in tools]
def called_tools(result) -> list[str]:
return [c["name"] for m in result["messages"] for c in (getattr(m, "tool_calls", None) or [])]
async def main():
agent = await build_agent(
model="openai:gpt-5-mini",
servers={"platform": StdioServerSpec(command=sys.executable, args=["platform_server.py"])},
optimize_tools="semantic", # each request gets only the tools that fit it
)
try:
direct = FirstCallTools()
await agent.ainvoke(
{
"messages": [
{
"role": "user",
"content": "The last deploy of prj_web_shop broke checkout. "
"Put production back the way it was.",
}
]
},
config={"callbacks": [direct]},
)
history = [
{
"role": "user",
"content": "The last deploy of prj_web_shop broke checkout. "
"What can we do? Don't change anything yet.",
}
]
first = await agent.ainvoke({"messages": history})
history.append({"role": "assistant", "content": first["messages"][-1].content})
history.append({"role": "user", "content": "Yes, go ahead."})
follow = FirstCallTools()
second = await agent.ainvoke({"messages": history}, config={"callbacks": [follow]})
print("One message:", direct.tools)
print("Follow-up: ", follow.tools)
print("first reply:", " ".join(first["messages"][-1].content.split())[:300])
print("after 'Yes, go ahead.' it called:", called_tools(second))
print("and answered:", " ".join(second["messages"][-1].content.split())[:300])
finally:
await agent.shutdown()
asyncio.run(main())One message: ['delete_project', 'archive_project', 'rollback_deployment', 'promote_deployment', 'redeploy', 'retry_webhook_delivery', 'resolve_incident', 'post_incident_update', 'request_more_tools']
Follow-up: ['update_user', 'transfer_ownership', 'update_webhook', 'update_database', 'update_incident', 'delete_incident', 'resolve_incident', 'post_incident_update', 'request_more_tools']
after 'Yes, go ahead.' it called: ['request_more_tools']The assistant's first reply was a long plan with several options, and "Yes, go ahead." is three words with no topic of their own. So the query was mostly the reply, and rollback_deployment dropped out. The model called request_more_tools and asked which option to run. If your agent proposes an action and waits for a yes, make the proposal name that one action. A short, specific proposal keeps its tool in the selection.
[08]
The other fix: fewer, better tools
Selection works around a big tool list. The other strategy is to not have one. Many MCP servers are a one-to-one copy of a REST API, so they inherit dozens of look-alike CRUD endpoints. MCPcast, Promptise's OpenAPI-to-MCP generator, takes the opposite approach: it drops what agents shouldn't touch and can merge related endpoints into one well-named tool. On the Swagger Petstore it turned 19 operations into 12 tools. OpenAPI to MCP: Turn Any REST API into an MCP Server walks through it.
The two combine well. Curate the servers you own. Use semantic selection for the ones you don't, or when the total is still over a hundred.
[09]
Common mistakes with LLM tool selection
Cutting the sentence that says when to use a tool. The semantic preset embeds the first 100 characters of each description. Raise max_description_length, or move the "when to use it" to the front.
Counting on the model to ask for more tools. It sometimes does. Just as often it uses the closest tool it has, which can be heavier than the one you wanted.
Treating selection as a permission system. A tool that wasn't offered still runs if the model calls it by name. Use approval or server-side checks for tools that change or delete things.
Stripping parameter descriptions that carry hints. Every preset removes parameter descriptions such as
The environment ID, for example "env_prod". Without them, a model may go looking for an ID the request already gave. Put such hints in the parameter name or the tool description, or list the tool in preserve_tools.Setting
semantic_top_kvery low. Fewer tools per call saves little once you are at 8, and raises the chance that the right one is missing.Counting tools per server. The provider limit applies to the request. Two ordinary servers can cross 128 together.
Switching embedding models on faith. Run the retrieval check with your own requests before and after.
Tools that return nothing useful. An empty or vague result makes the model try again until the iteration limit. Return a clear "no events found" and catch GraphIterationLimitError.
Expecting the token savings to show up 1:1 on the bill. A request with all 122 definitions is the same at the start every time, so OpenAI can serve much of it from its prompt cache at a discount. The short semantic prompts often fall under the minimum length for caching. The cost gap is smaller than the token gap.
[10]
Frequently asked questions
How many tools can an LLM handle?
It depends on the model and on how alike the tools are. OpenAI suggests fewer than 20 at the start of a turn and rejects more than 128, and Anthropic says Claude's tool selection degrades past 30 to 50. A capable model can pick well from more than 100 clearly described tools, so cost, latency and provider limits usually set the ceiling before accuracy does.
How many tools should an LLM agent see per call?
As few as the task needs, as long as the right one is among them. Semantic selection's default is 8 plus a fallback, so on a 122-tool server the model gets 9 tool definitions instead of 122. Check with your real requests that the right tool makes the top 8, as in the retrieval check above.
What is semantic tool selection?
Choosing which tools to offer the model by embedding similarity. The tool descriptions are embedded once, the recent conversation is embedded before each model call, and only the closest matches go to the model. It's also called tool retrieval or dynamic tool selection. In Promptise Foundry it's build_agent(optimize_tools="semantic"), and it runs locally with sentence-transformers.
Why does my agent pick the wrong MCP tool?
Usually because the right tool wasn't offered or its description doesn't say when to use it. Print the tools each model call receives, as watch_selection.py does, and run your requests through ToolIndex. If the right tool is missing, keep whole descriptions, lead them with the situations people describe, or try another embedding model.
Does tool selection work with any MCP server?
Yes. Optimization happens in the agent, after it lists the servers' tools, so the servers don't need to change. It works with any tool-calling model, because the model just receives a shorter tool list.
Is it better to merge tools or to filter them?
Merge when you own the server: fewer, clearer tools help every client, not just your agent. Filter when you don't own the server, or when you connect so many that even good tools add up to more than a hundred.
[11]
Where to go next
Tool Optimization: every ToolOptimizationConfig option and preset.
Building Agents: the rest of build_agent.
Observability: track token usage across your agents.
MCPcast reference: generate a curated MCP server from an OpenAPI spec.
OpenAPI to MCP: Turn Any REST API into an MCP Server: fewer, better tools in practice.
How to Connect MCP Servers to Your AI Agent in Python: the agent and server basics this guide builds on.
What Is Tool Calling?: how tool definitions reach the model on every call.
Tool Result Too Large?: the other side of the context bill, when one tool returns too much.
Context Engineering for AI Agents: what else goes into the context window, and how to keep it small.