Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions cyclops/core/agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
from cyclops.core.session import Session
from cyclops.core.subagents import AgentTool
from cyclops.core.sync import _iterate_sync, _run_coroutine_sync
from cyclops.core.tool_search import SEARCH_TOOL_NAME
from cyclops.core.types import AgentConfig, RunResult
from cyclops.skills import Skills
from cyclops.toolkit.types import ToolAnnotations
Expand All @@ -32,6 +33,10 @@ def __init__(
if t.name in self._tools_by_name:
raise ValueError(f"Duplicate tool name: '{t.name}'")
self._tools_by_name[t.name] = t
if SEARCH_TOOL_NAME in self._tools_by_name and any(
t.defer_loading for t in self.tools
):
raise ValueError(f"'{SEARCH_TOOL_NAME}' is taken by the search tool")
# Set to "naive" once this agent's model rejects native tool calling.
self._detected_tool_mode: Optional[str] = None

Expand Down
16 changes: 13 additions & 3 deletions cyclops/core/run.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@
_parse_naive_tool_call,
_ToolExecutor,
)
from cyclops.core.tool_search import _ToolSearch
from cyclops.core.types import AgentConfig, RunResult, StopReason
from cyclops.skills import Skills

Expand Down Expand Up @@ -186,9 +187,10 @@ async def _steps(self, input_message: str, mode: str) -> None:
naive = mode == "naive"
# Naive mode never streams deltas: the text may be a tool call.
streamed = self.stream and not naive
kwargs = _completion_kwargs(self.config, agent.tools, mode, self.response_model)
system_prompt = _system_prompt(self.config, agent.skills, agent.tools, mode)
executor = _ToolExecutor(self.config, agent._tools_by_name, run)
tools = _ToolSearch(agent.tools, agent._tools_by_name)
Comment thread
gopaljigaur marked this conversation as resolved.
Resolved
kwargs: Dict[str, Any] = {}
system_prompt: Optional[str] = None
executor = _ToolExecutor(self.config, tools.tools_by_name, run)

guard_rounds = 0
# Guard feedback waiting to be sent once another step is allowed.
Expand All @@ -199,6 +201,14 @@ async def _steps(self, input_message: str, mode: str) -> None:
if run.over_budget():
result.stop_reason = "budget"
return
if tools.changed:
Comment thread
gopaljigaur marked this conversation as resolved.
Resolved
tools.changed = False
kwargs = _completion_kwargs(
self.config, tools.loaded, mode, self.response_model
)
system_prompt = _system_prompt(
self.config, agent.skills, tools.loaded, mode
)
if feedback is not None:
run.history.append({"role": "user", "content": feedback})
feedback = None
Expand Down
71 changes: 71 additions & 0 deletions cyclops/core/tool_search.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
"""Deferred tools: a search tool that loads them into a run as the model finds them."""

import re
from typing import Any, Dict, List, Set

from cyclops.toolkit.tool import Tool
from cyclops.toolkit.types import ToolAnnotations

SEARCH_TOOL_NAME = "search_tools"

# Most tools one search returns, as Pydantic AI's keyword search.
_MAX_RESULTS = 10

_DESCRIPTION = (
"Search for more tools by keywords that describe what you need. The "
"tools found are loaded and can be called from the next step on."
)


def _words(text: str) -> Set[str]:
"""Lowercased words, splitting names like read_file at underscores."""
return set(re.findall(r"[^\W_]+", text.lower()))


class _ToolSearch:
"""The tools of one run: those always sent, plus the deferred ones found so far.

With any tool deferred, the tools sent include a search tool over them.
"""

def __init__(self, tools: List[Any], tools_by_name: Dict[str, Any]) -> None:
self.loaded = [t for t in tools if not t.defer_loading]
self.tools_by_name = tools_by_name
# Each deferred tool with the words of its name and description.
self._index = [
(t, _words(f"{t.name} {t.description}")) for t in tools if t.defer_loading
]
# True until the step loop has read loaded, and again after a search adds to it.
self.changed = True
if self._index:
search = Tool(
SEARCH_TOOL_NAME,
_DESCRIPTION,
self.search,
ToolAnnotations(read_only=True),
)
self.loaded.append(search)
self.tools_by_name = {**tools_by_name, SEARCH_TOOL_NAME: search}

async def search(self, query: str) -> str:
"""Find deferred tools by the words their name and description share with query.

Args:
query: Keywords such as "read file" or "calendar event".
"""
words = _words(query)
scores = [(len(words & tool_words), t) for t, tool_words in self._index]
# Tools not loaded yet first, so loaded ones never crowd them out.
ranked = sorted(
((score, t) for score, t in scores if score),
key=lambda s: (s[1] in self.loaded, -s[0]),
)
found = [t for _, t in ranked[:_MAX_RESULTS]]
if not found:
return f"No tools match '{query}'."
new = [t for t in found if t not in self.loaded]
if new:
self.loaded += new
self.changed = True
listing = "".join(f"\n- {t.name}: {t.description}" for t in found)
return f"These tools can now be called:{listing}"
4 changes: 3 additions & 1 deletion cyclops/mcp/bridge.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,9 @@ class _BridgeTool(MCPClientTool):

def __init__(self, loop: asyncio.AbstractEventLoop, tool: MCPClientTool) -> None:
self._loop = loop
super().__init__(tool.client, tool.server, tool.tool, tool.name)
super().__init__(
tool.client, tool.server, tool.tool, tool.name, tool.defer_loading
)

async def execute(self, **kwargs: Any) -> ToolResult:
if self._loop.is_closed():
Expand Down
20 changes: 15 additions & 5 deletions cyclops/mcp/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ async def attach(
call_timeout: Optional[float] = DEFAULT_CALL_TIMEOUT,
idle_timeout: Optional[float] = None,
reconnection: ReconnectionOptions = ReconnectionOptions(),
defer_loading: bool = False,
) -> List[MCPClientTool]:
"""Connect to a server and return its tools.

Expand All @@ -72,8 +73,10 @@ async def attach(
``OAuthClientProvider``. ``prefix`` is ``True`` for the server name,
a string, or ``False`` for none. ``call_timeout`` bounds each call;
``idle_timeout`` closes a session no call has used for that long.
``None`` disables either. Attaching an existing name replaces that
server. The server's tools must be awaited on the loop that attached it.
``None`` disables either. ``defer_loading`` defers every tool of the
server, so the model finds them with the agent's search tool.
Attaching an existing name replaces that server. The server's tools
must be awaited on the loop that attached it.
"""
if (command is None) == (url is None):
raise ValueError("Pass exactly one of command or url")
Expand All @@ -92,28 +95,35 @@ async def attach(
call_timeout=call_timeout,
idle_timeout=idle_timeout,
reconnection=reconnection,
on_tools_changed=functools.partial(self._set_tools, name, label),
on_tools_changed=functools.partial(
self._set_tools, name, label, defer_loading
),
)
session = await conn.connect()
try:
async with asyncio_timeout(connect_timeout):
remote_tools = await conn.list_tools(session)
tools = self._set_tools(name, label, remote_tools)
tools = self._set_tools(name, label, defer_loading, remote_tools)
except BaseException:
await conn.detach()
raise
self._connections[name] = conn
return tools

def _set_tools(
self, name: str, label: Union[str, bool], remote_tools: List[Tool]
self,
name: str,
label: Union[str, bool],
defer_loading: bool,
remote_tools: List[Tool],
) -> List[MCPClientTool]:
tools = [
MCPClientTool(
client=self,
server=name,
tool=t,
name=f"{label}__{t.name}" if label else t.name,
defer_loading=defer_loading,
)
for t in remote_tools
]
Expand Down
8 changes: 7 additions & 1 deletion cyclops/mcp/tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -86,11 +86,17 @@ def __init__(
server: str,
tool: mcp_types.Tool,
name: Optional[str] = None,
defer_loading: bool = False,
) -> None:
self.client = client
self.server = server
self.tool = tool
super().__init__(name or tool.name, tool.description or "", _annotations(tool))
super().__init__(
name or tool.name,
tool.description or "",
_annotations(tool),
defer_loading=defer_loading,
)

def _build_definition(self) -> ToolDefinition:
return ToolDefinition(
Expand Down
5 changes: 4 additions & 1 deletion cyclops/toolkit/decorators.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ def tool(
registry: Optional[ToolRegistry] = None,
annotations: Optional[ToolAnnotations] = None,
timeout: Optional[float] = None,
defer_loading: bool = False,
) -> Union[Tool, Callable[[Callable], Tool]]:
"""Decorator to convert a function into a tool

Expand Down Expand Up @@ -50,7 +51,9 @@ def decorator(f: Callable) -> Tool:
description or (summary or "").strip() or f"Tool: {tool_name}"
)

created_tool = Tool(tool_name, tool_description, f, annotations, timeout)
created_tool = Tool(
tool_name, tool_description, f, annotations, timeout, defer_loading
)

if registry:
registry.register(created_tool)
Expand Down
6 changes: 5 additions & 1 deletion cyclops/toolkit/tool.py
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,7 @@ def __init__(
description: str,
annotations: Optional[ToolAnnotations] = None,
timeout: Optional[float] = None,
defer_loading: bool = False,
):
self.name = name
self.description = description
Expand All @@ -116,6 +117,8 @@ def __init__(
self.annotations = annotations or ToolAnnotations()
# Seconds a call may run; None uses AgentConfig.tool_timeout.
self.timeout = timeout
# Sent only once the model finds it with the search_tools tool.
self.defer_loading = defer_loading
self._definition = self._build_definition()

async def execute(self, **kwargs):
Expand Down Expand Up @@ -152,6 +155,7 @@ def __init__(
func: Callable,
annotations: Optional[ToolAnnotations] = None,
timeout: Optional[float] = None,
defer_loading: bool = False,
):
self.func = func
self._is_async = inspect.iscoroutinefunction(func)
Expand All @@ -160,7 +164,7 @@ def __init__(
for p in inspect.signature(func).parameters.values()
if p.kind is p.POSITIONAL_ONLY
]
super().__init__(name, description, annotations, timeout)
super().__init__(name, description, annotations, timeout, defer_loading)

def _build_definition(self) -> ToolDefinition:
return self._definition_for(self.func)
Expand Down
4 changes: 4 additions & 0 deletions docs/api-reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -324,6 +324,7 @@ def tool(
registry: Optional[ToolRegistry] = None,
annotations: Optional[ToolAnnotations] = None,
timeout: Optional[float] = None,
defer_loading: bool = False,
) -> Union[Tool, Callable[[Callable], Tool]]: ...
```

Expand All @@ -341,6 +342,7 @@ class BaseTool(ABC):
description: str,
annotations: Optional[ToolAnnotations] = None,
timeout: Optional[float] = None,
defer_loading: bool = False,
): ...
async def execute(self, **kwargs) -> Any: ...

Expand All @@ -363,6 +365,7 @@ class Tool(BaseTool):
func: Callable,
annotations: Optional[ToolAnnotations] = None,
timeout: Optional[float] = None,
defer_loading: bool = False,
): ...
async def execute(self, **kwargs) -> Any: ...
```
Expand Down Expand Up @@ -476,6 +479,7 @@ class MCPClient:
call_timeout: Optional[float] = 60.0,
idle_timeout: Optional[float] = None,
reconnection: ReconnectionOptions = ReconnectionOptions(),
defer_loading: bool = False,
) -> List[MCPClientTool]: ...
async def detach(self, name: str) -> None: ...
async def aclose(self) -> None: ...
Expand Down
8 changes: 8 additions & 0 deletions docs/guide/mcp.md
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,14 @@ await mcp.attach("plain", ["python", "mcp_server.py"], prefix=False) # add

The server's input schema is sent to the model as is, including nested objects and `$defs`.

### Deferred tools

A server with many tools can keep them out of every completion until the model searches for them. `defer_loading=True` defers each tool of the server, including ones it lists later; see [Deferred tools](tools.md#deferred-tools):

```python
await mcp.attach("crm", url="https://example.com/mcp", defer_loading=True)
```

### Results

`execute()` returns a `ToolResult`. Text and image content become its `content` blocks (`TextContent`, `ImageContent`) and `structuredContent` becomes its `result`; the agent sends it to the model like any other tool result. A result with `isError` set becomes an error result carrying the server's text. The server's tool annotations (`readOnlyHint` and the others) become the tool's `ToolAnnotations`.
Expand Down
29 changes: 29 additions & 0 deletions docs/guide/tools.md
Original file line number Diff line number Diff line change
Expand Up @@ -178,6 +178,35 @@ def build_report(month: str) -> str:

A call that runs over is cancelled and the model gets `Error: <tool> timed out after <n> seconds`. Middleware `after_tool`, `on_tool_error` and the `ToolCallFinished` event see it as any other failed call, with an `asyncio.TimeoutError`. A sync tool runs in a worker thread, which cannot be stopped: the agent moves on, but the function runs until it returns. MCP tools also have the client's own `call_timeout`.

## Deferred tools

Every tool's schema is sent with every completion, which costs context when an agent has many tools. Mark a tool `defer_loading=True` and it is left out until the model asks for it: the agent then sends a `search_tools` tool, and each tool a search finds is sent from the next step to the end of the run. Tools not marked are always sent.

```python
@tool(defer_loading=True)
def create_invoice(customer: str, amount: float) -> str:
"""Create an invoice for a customer."""
...
```

`BaseTool` subclasses pass `defer_loading=` to `super().__init__()`, and `MCPClient.attach(..., defer_loading=True)` defers every tool of that server.

`search_tools` takes a `query` of keywords and returns up to ten deferred tools that share words with their name and description (names split at underscores), most shared words first, with tools not loaded yet ahead of loaded ones. The model gets their names and descriptions; their schemas arrive with the next completion, or in the system prompt in naive tool mode. A deferred tool the model calls by name without searching still runs. With any tool deferred, `search_tools` is a reserved name.

Found tools last for the run. The next run, in a session too, starts again from the tools that are always sent, and the model searches again for what it needs.

`search_tools` goes through middleware like any other tool. With `ToolPermissions(default="deny")`, allow it, or no deferred tool can load:

```python
ToolPermissions(default="deny", allow=["read_*", "search_tools"])
```

A deferred tool that a rule denies is still found, and denied when called.

A search that adds tools changes what is sent before the conversation: the tools, which come first in the prompt, or the system prompt in naive tool mode. The next completion misses the prompt cache and writes it again over the tools, the system prompt and the history; later steps hit it again. The first completion of the next run misses as well, as it goes back to the tools always sent.

The search runs in the agent for every provider, Anthropic included. Anthropic's and OpenAI's own tool search keep the tools sent unchanged and so keep the cache; using them is tracked in [#113](https://github.com/gopaljigaur/cyclops/issues/113).

## ToolRegistry

`ToolRegistry` is a named collection of tools. It is useful when you want to manage a set of tools separately from any single agent, such as in a plugin or a shared tool library.
Expand Down
Loading
Loading