Skip to content

tool_bridge

Class info

Classes

Name Children Inherits
ToolBridge
llmling_models.tool_bridge
Exposes Python functions as an MCP server.
    ToolBridgeConfig
    llmling_models.tool_bridge
    Configuration for the ToolBridge.

      🛈 DocStrings

      MCP server bridge for exposing Python functions to MCP clients.

      This module provides a bridge that exposes Python functions as an MCP server using HTTP transport. This allows Agents to use custom tools which have runtime access to our internals via Context objects.

      The bridge runs in-process and handles the MCP protocol automatically.

      MCPTransport module-attribute

      MCPTransport = Literal['http', 'streamable-http', 'sse']
      

      Transports supported for serving the tool bridge.

      ToolBridge dataclass

      Exposes Python functions as an MCP server.

      This bridge lets an MCP client (a model or agent that can connect to MCP servers) call custom Python functions via MCP transport.

      Example
      def my_tool(x: int) -> int:
          '''Double the input.'''
          return x * 2
      
      async with ToolBridge(tools=[my_tool]) as bridge:
          mcp_tool = bridge.get_mcp_server_tool()
          # Pass NativeTool(mcp_tool) to the agent's capabilities
      
      Source code in src/llmling_models/tool_bridge.py
      @dataclass
      class ToolBridge:
          """Exposes Python functions as an MCP server.
      
          This bridge lets an MCP client (a model or agent that can connect to MCP
          servers) call custom Python functions via MCP transport.
      
          Example:
              ```python
              def my_tool(x: int) -> int:
                  '''Double the input.'''
                  return x * 2
      
              async with ToolBridge(tools=[my_tool]) as bridge:
                  mcp_tool = bridge.get_mcp_server_tool()
                  # Pass NativeTool(mcp_tool) to the agent's capabilities
              ```
          """
      
          tools: list[Callable[..., Any]]
          """The functions to expose as tools."""
      
          config: ToolBridgeConfig = field(default_factory=ToolBridgeConfig)
          """Bridge configuration."""
      
          _mcp: FastMCP | None = field(default=None, init=False, repr=False)
          """FastMCP server instance."""
      
          _server: Server | None = field(default=None, init=False, repr=False)
          """Uvicorn server instance."""
      
          _server_task: asyncio.Task[None] | None = field(default=None, init=False, repr=False)
          """Background task running the server."""
      
          _actual_port: int | None = field(default=None, init=False, repr=False)
          """Actual port the server is bound to."""
      
          _tool_funcs: dict[str, Callable[..., Any]] = field(default_factory=dict, init=False, repr=False)
          """Mapping of tool names to their callables."""
      
          _tool_args: dict[str, type[BaseModel]] = field(default_factory=dict, init=False, repr=False)
          """Mapping of tool names to the models validating their arguments."""
      
          async def __aenter__(self) -> Self:
              """Start the MCP server."""
              await self.start()
              return self
      
          async def __aexit__(self, *args: object) -> None:
              """Stop the MCP server."""
              await self.stop()
      
          async def start(self) -> None:
              """Start the HTTP MCP server in the background."""
              from fastmcp import FastMCP
      
              self._mcp = FastMCP(name=self.config.server_name)
              self._register_tools()
              await self._start_server()
      
          async def stop(self) -> None:
              """Stop the HTTP MCP server."""
              if self._server:
                  self._server.should_exit = True
                  if self._server_task:
                      try:
                          await asyncio.wait_for(self._server_task, timeout=5.0)
                      except TimeoutError:
                          self._server_task.cancel()
                          with suppress(asyncio.CancelledError):
                              await self._server_task
                  self._server = None
                  self._server_task = None
              self._mcp = None
              self._actual_port = None
              self._tool_funcs.clear()
              self._tool_args.clear()
      
          @property
          def port(self) -> int:
              """Get the actual port the server is running on."""
              if self._actual_port is None:
                  msg = "Server not started"
                  raise RuntimeError(msg)
              return self._actual_port
      
          @property
          def url(self) -> str:
              """Get the server URL."""
              path = "/sse" if self.config.transport == "sse" else "/mcp"
              return f"http://{self.config.host}:{self.port}{path}"
      
          def get_mcp_server_tool(self) -> MCPServerTool:
              """Get a pydantic-ai MCPServerTool for a model that supports MCP servers.
      
              Returns:
                  MCPServerTool configured to connect to this bridge.
              """
              return MCPServerTool(id=self.config.server_name, url=self.url)
      
          def _register_tools(self) -> None:
              """Register all functions with the FastMCP server."""
              if not self._mcp:
                  return
      
              for func in self.tools:
                  self._register_single_tool(func)
      
          def _register_single_tool(self, func: Callable[..., Any]) -> None:
              """Register a single function with the FastMCP server."""
              if not self._mcp:
                  return
      
              from fastmcp.tools import Tool as FastMCPTool
      
              name = getattr(func, "__name__", "unknown")
              description = _get_function_description(func)
              args_model = _get_args_model(func)
              parameters = _get_function_schema(func, args_model)
              # Store the function for invocation
              self._tool_funcs[name] = func
              self._tool_args[name] = args_model
              # Create wrapper that bridges to our invocation
              bridge = self
      
              class BridgedTool(FastMCPTool):
                  """FastMCP tool that wraps a Python function."""
      
                  def __init__(self) -> None:
                      super().__init__(name=name, description=description, parameters=parameters)
      
                  async def run(
                      self, arguments: dict[str, Any], context: Context | None = None
                  ) -> ToolResult:
                      """Execute the wrapped function."""
                      result = await bridge._invoke_tool(name, arguments)
                      return _convert_to_tool_result(result)
      
              self._mcp.add_tool(BridgedTool())
      
          async def _invoke_tool(self, tool_name: str, arguments: dict[str, Any]) -> Any:
              """Invoke a tool function."""
              if tool_name not in self._tool_funcs:
                  raise KeyError(f"Tool {tool_name!r} not found")
      
              func = self._tool_funcs[tool_name]
              # Validate and convert like a pydantic-ai tool would (dicts to models, ...).
              args_model = self._tool_args.get(tool_name) or _get_args_model(func)
              validated = args_model.model_validate(arguments)
              kwargs = {name: getattr(validated, name) for name in args_model.model_fields}
              if inspect.iscoroutinefunction(func):
                  return await func(**kwargs)
              # Sync tools run in a thread: the loop also serves the bridge and the agent.
              result = await asyncio.to_thread(func, **kwargs)
              if inspect.isawaitable(result):
                  result = await result
              return result
      
          async def _start_server(self) -> None:
              """Start the uvicorn server in the background."""
              import uvicorn
      
              if not self._mcp:
                  raise RuntimeError("MCP server not initialized")
      
              # Determine actual port (auto-select if 0)
              port = self.config.port
              if port == 0:
                  with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
                      s.bind((self.config.host, 0))
                      port = s.getsockname()[1]
              self._actual_port = port
              # Create the ASGI app
              app = self._mcp.http_app(transport=self.config.transport)
              # Configure uvicorn
              cfg = uvicorn.Config(app=app, host=self.config.host, port=port, log_level="warning")
              self._server = uvicorn.Server(cfg)
              # Start server in background task
              name = f"tool-bridge-{self.config.server_name}"
              self._server_task = asyncio.create_task(self._server.serve(), name=name)
              # Wait briefly for server to start
              await asyncio.sleep(0.1)
      

      config class-attribute instance-attribute

      config: ToolBridgeConfig = field(default_factory=ToolBridgeConfig)
      

      Bridge configuration.

      port property

      port: int
      

      Get the actual port the server is running on.

      tools instance-attribute

      tools: list[Callable[..., Any]]
      

      The functions to expose as tools.

      url property

      url: str
      

      Get the server URL.

      __aenter__ async

      __aenter__() -> Self
      

      Start the MCP server.

      Source code in src/llmling_models/tool_bridge.py
      async def __aenter__(self) -> Self:
          """Start the MCP server."""
          await self.start()
          return self
      

      __aexit__ async

      __aexit__(*args: object) -> None
      

      Stop the MCP server.

      Source code in src/llmling_models/tool_bridge.py
      async def __aexit__(self, *args: object) -> None:
          """Stop the MCP server."""
          await self.stop()
      

      get_mcp_server_tool

      get_mcp_server_tool() -> MCPServerTool
      

      Get a pydantic-ai MCPServerTool for a model that supports MCP servers.

      Returns:

      Type Description
      MCPServerTool

      MCPServerTool configured to connect to this bridge.

      Source code in src/llmling_models/tool_bridge.py
      def get_mcp_server_tool(self) -> MCPServerTool:
          """Get a pydantic-ai MCPServerTool for a model that supports MCP servers.
      
          Returns:
              MCPServerTool configured to connect to this bridge.
          """
          return MCPServerTool(id=self.config.server_name, url=self.url)
      

      start async

      start() -> None
      

      Start the HTTP MCP server in the background.

      Source code in src/llmling_models/tool_bridge.py
      async def start(self) -> None:
          """Start the HTTP MCP server in the background."""
          from fastmcp import FastMCP
      
          self._mcp = FastMCP(name=self.config.server_name)
          self._register_tools()
          await self._start_server()
      

      stop async

      stop() -> None
      

      Stop the HTTP MCP server.

      Source code in src/llmling_models/tool_bridge.py
      async def stop(self) -> None:
          """Stop the HTTP MCP server."""
          if self._server:
              self._server.should_exit = True
              if self._server_task:
                  try:
                      await asyncio.wait_for(self._server_task, timeout=5.0)
                  except TimeoutError:
                      self._server_task.cancel()
                      with suppress(asyncio.CancelledError):
                          await self._server_task
              self._server = None
              self._server_task = None
          self._mcp = None
          self._actual_port = None
          self._tool_funcs.clear()
          self._tool_args.clear()
      

      ToolBridgeConfig dataclass

      Configuration for the ToolBridge.

      Source code in src/llmling_models/tool_bridge.py
      @dataclass
      class ToolBridgeConfig:
          """Configuration for the ToolBridge."""
      
          host: str = "127.0.0.1"
          """Host to bind the HTTP server to."""
      
          port: int = 0
          """Port to bind to (0 = auto-select available port)."""
      
          transport: MCPTransport = "sse"
          """Transport protocol: 'sse' or 'streamable-http'."""
      
          server_name: str = "pydantic-ai-tools"
          """Name for the MCP server."""
      

      host class-attribute instance-attribute

      host: str = '127.0.0.1'
      

      Host to bind the HTTP server to.

      port class-attribute instance-attribute

      port: int = 0
      

      Port to bind to (0 = auto-select available port).

      server_name class-attribute instance-attribute

      server_name: str = 'pydantic-ai-tools'
      

      Name for the MCP server.

      transport class-attribute instance-attribute

      transport: MCPTransport = 'sse'
      

      Transport protocol: 'sse' or 'streamable-http'.

      create_tool_bridge async

      create_tool_bridge(
          tools: list[Callable[..., Any]],
          *,
          host: str = "127.0.0.1",
          port: int = 0,
          transport: MCPTransport = "sse",
          server_name: str = "pydantic-ai-tools",
      ) -> AsyncGenerator[ToolBridge]
      

      Create and start a ToolBridge as a context manager.

      Parameters:

      Name Type Description Default
      tools list[Callable[..., Any]]

      Functions to expose as MCP tools

      required
      host str

      Host to bind to

      '127.0.0.1'
      port int

      Port to bind to (0 = auto-select)

      0
      transport MCPTransport

      Transport protocol ('sse' or 'streamable-http')

      'sse'
      server_name str

      Name for the MCP server

      'pydantic-ai-tools'

      Yields:

      Type Description
      AsyncGenerator[ToolBridge]

      Running ToolBridge instance

      Example
      def greet(name: str) -> str:
          return f"Hello, {name}!"
      
      async with create_tool_bridge([greet]) as bridge:
          mcp_tool = bridge.get_mcp_server_tool()
          # Pass NativeTool(mcp_tool) to the agent's capabilities
      
      Source code in src/llmling_models/tool_bridge.py
      @asynccontextmanager
      async def create_tool_bridge(
          tools: list[Callable[..., Any]],
          *,
          host: str = "127.0.0.1",
          port: int = 0,
          transport: MCPTransport = "sse",
          server_name: str = "pydantic-ai-tools",
      ) -> AsyncGenerator[ToolBridge]:
          """Create and start a ToolBridge as a context manager.
      
          Args:
              tools: Functions to expose as MCP tools
              host: Host to bind to
              port: Port to bind to (0 = auto-select)
              transport: Transport protocol ('sse' or 'streamable-http')
              server_name: Name for the MCP server
      
          Yields:
              Running ToolBridge instance
      
          Example:
              ```python
              def greet(name: str) -> str:
                  return f"Hello, {name}!"
      
              async with create_tool_bridge([greet]) as bridge:
                  mcp_tool = bridge.get_mcp_server_tool()
                  # Pass NativeTool(mcp_tool) to the agent's capabilities
              ```
          """
          config = ToolBridgeConfig(
              host=host,
              port=port,
              transport=transport,
              server_name=server_name,
          )
          bridge = ToolBridge(tools=tools, config=config)
          async with bridge:
              yield bridge