from __future__ import annotations
from dataclasses import asdict
from typing import Any, cast
from pydantic_core import to_jsonable_python
from ._generated.tools import ANTHROPIC_TOOLS, OPENAI_TOOLS
from ._generated.tools import arun as _arun
from ._generated.tools import run as _run
from ._core.ops import Done, Held
from .client import AsyncSailfork, Sailfork
__all__ = ["ANTHROPIC_TOOLS", "OPENAI_TOOLS", "arun", "run"]
_shared: Sailfork | None = None
def _jsonable(result: Any) -> Any:
if isinstance(result, Held):
return {k: v for k, v in asdict(result).items() if v is not None}
if isinstance(result, Done):
done = cast("Done[Any]", result)
return {"status": done.status, "value": to_jsonable_python(done.value, by_alias=True)}
return to_jsonable_python(result, by_alias=True)
def run(name: str, input: dict[str, Any], *, client: Sailfork | None = None) -> Any:
"""Runs the tool a model called, by its MCP name, with the tool's input. Uses `client`, else one built from the environment."""
global _shared
if client is None:
_shared = _shared or Sailfork()
client = _shared
return _jsonable(_run(client._core, name, input)) # pyright: ignore[reportPrivateUsage]
async def arun(name: str, input: dict[str, Any], *, client: AsyncSailfork | None = None) -> Any:
"""`run` for asyncio. Without `client` it opens one for the call and closes it after."""
if client is not None:
return _jsonable(await _arun(client._core, name, input)) # pyright: ignore[reportPrivateUsage]
async with AsyncSailfork() as own:
return _jsonable(await _arun(own._core, name, input)) # pyright: ignore[reportPrivateUsage]