### Start SSE Server and Use MCPAdapt Source: https://context7.com/grll/mcpadapt/llms.txt Illustrates starting a local SSE server and then connecting to it using MCPAdapt. Replace the local URL with a production URL when necessary. Ensure the server has sufficient time to start before making calls. ```python import subprocess import time from mcpadapt.core import MCPAdapt from mcpadapt.smolagents_adapter import SmolAgentsAdapter process = subprocess.Popen(["python", "-c", """ from mcp.server.fastmcp import FastMCP mcp = FastMCP("Echo Server") @mcp.tool() def echo_tool(text: str) -> str: """Echo the input text""" return f"Echo: {text}" mcp.run("sse") """]) time.sleep(1) # let the server start with MCPAdapt( { "url": "http://127.0.0.1:8000/sse", # "transport": "sse", # default, can be omitted # "headers": {"Authorization": "Bearer "}, # "timeout": 5, # "sse_read_timeout": 300, }, SmolAgentsAdapter(), ) as tools: print(tools[0]("hello")) # → "Echo: hello" process.terminate() ``` ```python async def streamable_http_example(): async with MCPAdapt( {"url": "http://127.0.0.1:8000/mcp", "transport": "streamable-http"}, SmolAgentsAdapter(), ) as tools: print(tools) ``` -------------------------------- ### Install Smolagents with MCP support Source: https://github.com/grll/mcpadapt/blob/main/README.md Install smolagents with the mcpadapt integration using uv. ```bash uv add smolagents[mcp] ``` -------------------------------- ### Install MCPAdapt with LangChain Support Source: https://github.com/grll/mcpadapt/blob/main/docs/guide/langchain.md Install the MCPAdapt library with the necessary dependencies for LangChain integration. ```bash pip install mcpadapt[langchain] ``` -------------------------------- ### Install MCPAdapt with Framework Support Source: https://github.com/grll/mcpadapt/blob/main/README.md Install mcpadapt with optional dependencies for specific agent frameworks like Langchain using uv or pip. ```bash # with uv uv add mcpadapt[langchain] # or with pip pip install mcpadapt[langchain] ``` -------------------------------- ### Install MCPAdapt with Framework Extras Source: https://context7.com/grll/mcpadapt/llms.txt Install MCPAdapt by selecting the extra package corresponding to your agent framework. Optional extras like 'audio' can be included. ```bash pip install mcpadapt[smolagents] pip install mcpadapt[langchain] pip install mcpadapt[crewai] pip install mcpadapt[google-genai] ``` ```bash # Optional audio content support (for Smolagents) pip install mcpadapt[smolagents,audio] ``` -------------------------------- ### Install mcpadapt with Agentic Framework Support Source: https://github.com/grll/mcpadapt/blob/main/docs/quickstart.md Install mcpadapt with the necessary extras for your chosen agentic framework. ```bash pip install mcpadapt[agentic-framework] ``` -------------------------------- ### Install MCPAdapt with Audio Support Source: https://github.com/grll/mcpadapt/blob/main/docs/guide/smolagents.md Install the MCPAdapt package with both smolagents and audio extras. This is required if you intend to use audio content features. ```bash uv add mcpadapt[smolagents,audio] ``` -------------------------------- ### Install MCPAdapt with Google GenAI Support Source: https://github.com/grll/mcpadapt/blob/main/docs/guide/google-genai.md Install the necessary dependencies for MCPAdapt with Google GenAI integration using pip. ```bash pip install mcpadapt[google-genai] ``` -------------------------------- ### Adapter Contribution Example Source: https://github.com/grll/mcpadapt/blob/main/docs/index.md Illustrates how to create a new adapter for an agentic framework. This involves defining a new module and implementing `adapt` and `async_adapt` methods to convert MCP tools into the target framework's tool format. ```python class Adapter(ToolAdapter): def adapt( self, func: Callable[[dict | None], mcp.types.CallToolResult], mcp_tool: mcp.types.Tool, ) -> YourFramework.Tool: # HERE implement how the adapter should convert a simple function and mcp_tool (JSON Schema) # into your framework tool. see smolagents_adapter.py for an example def async_adapt( self, afunc: Callable[[dict | None], Coroutine[Any, Any, mcp.types.CallToolResult]], mcp_tool: mcp.types.Tool, ) -> YourFramework.Tool: # if your framework supports async function even better use async_adapt. ``` -------------------------------- ### Configure MCP Server Parameters Source: https://github.com/grll/mcpadapt/blob/main/examples/notebook_usage.ipynb Set up the server parameters for running an MCP server, specifying the command, arguments, and environment variables. This example uses `uv` to run a local Python script. ```python # define the mcp server parameters to run serverparams = mcp.StdioServerParameters( command="uv", args=["--quiet", "run", "../src/echo.py"], env={"UV_PYTHON": "3.12", **os.environ}, ) ``` -------------------------------- ### Implement Custom ToolAdapter in Python Source: https://context7.com/grll/mcpadapt/llms.txt Subclass ToolAdapter and implement adapt/async_adapt to integrate MCPAdapt with custom frameworks. This example shows how to wrap MCP tools for a hypothetical framework. ```python from typing import Any, Callable, Coroutine import mcp from mcpadapt.core import ToolAdapter, MCPAdapt from mcp import StdioServerParameters class MyFrameworkAdapter(ToolAdapter): def adapt( self, func: Callable[[dict | None], mcp.types.CallToolResult], mcp_tool: mcp.types.Tool, ) -> Any: """Wrap the MCP tool as a plain callable dict for a hypothetical framework.""" return { "name": mcp_tool.name, "description": mcp_tool.description, "schema": mcp_tool.inputSchema, "call": func, # func({"arg": value}) → mcp.types.CallToolResult } def async_adapt( self, afunc: Callable[[dict | None], Coroutine[Any, Any, mcp.types.CallToolResult]], mcp_tool: mcp.types.Tool, ) -> Any: return { "name": mcp_tool.name, "description": mcp_tool.description, "schema": mcp_tool.inputSchema, "acall": afunc, # await afunc({"arg": value}) → mcp.types.CallToolResult } # Usage with MCPAdapt( StdioServerParameters(command="uv", args=["run", "src/echo.py"]), MyFrameworkAdapter(), ) as tools: tool = tools[0] result = tool["call"]({"text": "hello"}) print(result.content[0].text) # → "hello" ``` -------------------------------- ### Install Smolagents with MCP Support Source: https://github.com/grll/mcpadapt/blob/main/docs/guide/smolagents.md Install the smolagents package with MCP support using pip. ```bash pip install smolagents[mcp] ``` -------------------------------- ### MCPAdapt Manual Start/Close Pattern Source: https://context7.com/grll/mcpadapt/llms.txt Use explicit start() and close() methods when a context manager is not suitable. Call tools() after start() to refresh the tool list and close() to shut down cleanly. ```python from mcp import StdioServerParameters from mcpadapt.core import MCPAdapt from mcpadapt.smolagents_adapter import SmolAgentsAdapter adapter = MCPAdapt( StdioServerParameters(command="uv", args=["run", "src/echo.py"]), SmolAgentsAdapter(), ) adapter.start() tools = adapter.tools() # refreshes tool list from the server print(tools[0]("hello")) # call a tool # ... do more work ... adapter.close() # cleanly shuts down the background thread and event loop ``` -------------------------------- ### Adapt MCP Server for Agent Frameworks Source: https://github.com/grll/mcpadapt/blob/main/README.md Use MCPAdapt to integrate an MCP server into an agent framework, specifying server parameters and the desired adapter. This example uses StdioServerParameters and SmolAgentsAdapter. ```python from mcp import StdioServerParameters from mcpadapt.core import MCPAdapt from mcpadapt.smolagents_adapter import SmolAgentsAdapter with MCPAdapt( # specify the command to run your favorite MCP server (support also smithery and co.) StdioServerParameters(command="uv", args=["run", "src/echo.py"]), # or a dict of sse server parameters e.g. {"url": http://localhost:8000, "headers": ...} # specify the adapter you want to use to adapt MCP into your tool in this case smolagents. SmolAgentsAdapter(), ) as tools: # enjoy your smolagents tools as if you wrote them yourself ... ``` -------------------------------- ### Install MCPAdapt CrewAI Dependency Source: https://github.com/grll/mcpadapt/blob/main/docs/guide/crewai.md Install the MCPAdapt library with CrewAI support using pip. Ensure your OpenAI API key is set up as required by CrewAI. ```bash pip install mcpadapt[crewai] ``` -------------------------------- ### Google GenAI Function Calling with MCP Tools Source: https://context7.com/grll/mcpadapt/llms.txt Adapts MCP tools for Google's Gemini API using function calling. Requires the google-generativeai library and a GEMINI_API_KEY. This example demonstrates asynchronous tool execution. ```python import asyncio, os from google import genai from google.genai import types from mcp import StdioServerParameters from mcpadapt.core import MCPAdapt from mcpadapt.google_genai_adapter import GoogleGenAIAdapter client = genai.Client(api_key=os.environ["GEMINI_API_KEY"]) async def main(): async with MCPAdapt( StdioServerParameters( command="npx", args=["-y", "@openbnb/mcp-server-airbnb", "--ignore-robots-txt"], ), GoogleGenAIAdapter(), ) as adapted_tools: google_tools, tool_functions = zip(*adapted_tools) tool_functions = dict(tool_functions) # {name: async_callable} response = client.models.generate_content( model="gemini-2.0-flash", contents="Find apartments in Paris for 2 nights, Mar 28–30.", config=types.GenerateContentConfig(tools=list(google_tools)), ) part = response.candidates[0].content.parts[0] if part.function_call: fc = part.function_call print(f"Calling: {fc.name} with {fc.args}") result = await tool_functions[fc.name](fc.args) if not result.isError: print(result.content[0].text) else: print(response.text) asyncio.run(main()) ``` -------------------------------- ### Use PubMed MCP Server with CrewAI Source: https://github.com/grll/mcpadapt/blob/main/docs/guide/crewai.md Integrate with a pre-built PubMed MCP server using CrewAI. This example demonstrates loading environment variables, initializing MCPAdapt with specific server parameters, and creating a research agent to find studies. ```python import os from dotenv import load_dotenv from crewai import Agent, Crew, Task from mcp import StdioServerParameters from mcpadapt.core import MCPAdapt from mcpadapt.crewai_adapter import CrewAIAdapter # Load environment variables load_dotenv() if not os.environ.get("OPENAI_API_KEY"): raise ValueError("OPENAI_API_KEY must be set in your environment variables") # Initialize MCPAdapt with CrewAI adapter with MCPAdapt( StdioServerParameters( command="uvx", args=["--quiet", "pubmedmcp@0.1.3"], env={"UV_PYTHON": "3.12", **os.environ}, ), CrewAIAdapter(), ) as tools: # Create a research agent agent = Agent( role="Research Agent", goal="Find studies about hangover", backstory="You help find studies about hangover", verbose=True, tools=[tools[0]], ) # Create a task task = Task( description="Find studies about hangover", agent=agent, expected_output="A list of studies about hangover", ) # Create and run the crew crew = Crew(agents=[agent], tasks=[task], verbose=True) crew.kickoff() ``` -------------------------------- ### CrewAI Agent with MCP Tools Source: https://context7.com/grll/mcpadapt/llms.txt Wraps MCP tools for use with CrewAI agents. This adapter only supports synchronous tool usage. Ensure MCP and CrewAI are installed. ```python import os from crewai import Agent, Crew, Task from mcp import StdioServerParameters from mcpadapt.core import MCPAdapt from mcpadapt.crewai_adapter import CrewAIAdapter with MCPAdapt( StdioServerParameters( command="uvx", args=["--quiet", "pubmedmcp@0.1.3"], env={"UV_PYTHON": "3.12", **os.environ}, ), CrewAIAdapter(), ) as tools: agent = Agent( role="Research Agent", goal="Find studies about hangover", backstory="You are an expert at finding biomedical research.", verbose=True, tools=tools, # pass all tools or a subset ) task = Task( description="Find the top studies about hangover treatment published in the last 5 years.", agent=agent, expected_output="A bulleted list of study titles and abstracts.", ) crew = Crew(agents=[agent], tasks=[task], verbose=True) result = crew.kickoff() print(result) ``` -------------------------------- ### Aggregate Tools from Multiple MCP Servers Source: https://context7.com/grll/mcpadapt/llms.txt Demonstrates how to use MCPAdapt with a list of server parameters to combine tools from several MCP servers into a single list. This is useful for managing and accessing tools from different sources. ```python from mcp import StdioServerParameters from mcpadapt.core import MCPAdapt from mcpadapt.smolagents_adapter import SmolAgentsAdapter with MCPAdapt( [ StdioServerParameters(command="uv", args=["run", "src/server_a.py"]), StdioServerParameters(command="uv", args=["run", "src/server_b.py"]), {"url": "http://remote-mcp.example.com/sse"}, ], SmolAgentsAdapter(), ) as tools: # tools is a merged list from all three servers print(f"Total tools available: {len(tools)}") for t in tools: print(t.name) ``` -------------------------------- ### Sync MCP Adapt Usage Source: https://github.com/grll/mcpadapt/blob/main/examples/notebook_usage.ipynb Demonstrates how to use MCP Adapt in a synchronous context. This uses a `with` block to manage the server and interact with tools. ```python with MCPAdapt(serverparams, adapter=DummyToolAdapter()) as tools: echo_tool = tools[0] response = echo_tool({"text": "hello"}) print(response) ``` -------------------------------- ### Create a Simple Echo Server with FastMCP Source: https://github.com/grll/mcpadapt/blob/main/docs/guide/smolagents.md Define a basic echo server using FastMCP notation. This server will echo back any text it receives. ```python # echo.py from mcp.server.fastmcp import FastMCP from pydantic import Field # Create server mcp = FastMCP("Echo Server") @mcp.tool() def echo_tool(text: str = Field(description="The text to echo")) -> str: """Echo the input text Args: text (str): The text to echo Returns: str: The echoed text """ return text mcp.run() ``` -------------------------------- ### Async MCP Adapt Usage Source: https://github.com/grll/mcpadapt/blob/main/examples/notebook_usage.ipynb Demonstrates how to use MCP Adapt in an asynchronous context. This involves an `async with` block to manage the server and interact with tools. ```python async with MCPAdapt(serverparams, adapter=DummyToolAdapter()) as tools: echo_tool = tools[0] response = await echo_tool({"text": "hello"}) print(response) ``` -------------------------------- ### Create New Framework Adapter Source: https://github.com/grll/mcpadapt/blob/main/README.md Implement a new adapter by creating a Python module. Define `adapt` and `async_adapt` methods to convert framework-specific tools to MCP's format. See `smolagents_adapter.py` for a reference. ```python class YourFrameworkAdapter(ToolAdapter): def adapt( self, func: Callable[[dict | None], mcp.types.CallToolResult], mcp_tool: mcp.types.Tool, ) -> YourFramework.Tool: # HERE implement how the adapter should convert a simple function and mcp_tool (JSON Schema) # into your framework tool. see smolagents_adapter.py for an example def async_adapt( self, afunc: Callable[[dict | None], Coroutine[Any, Any, mcp.types.CallToolResult]], mcp_tool: mcp.types.Tool, ) -> YourFramework.Tool: # if your framework supports async function even better use async_adapt. ``` -------------------------------- ### Import MCP Adapt and Tooling Source: https://github.com/grll/mcpadapt/blob/main/examples/notebook_usage.ipynb Import necessary components from the mcpadapt and mcp libraries for using MCP Adapt. ```python import os from typing import Any, Callable, Coroutine from mcpadapt.core import MCPAdapt, ToolAdapter import mcp ``` -------------------------------- ### Create a Simple Echo Server with MCPAdapt Source: https://github.com/grll/mcpadapt/blob/main/docs/guide/langchain.md Defines a basic MCP server that echoes back the input text. This server can be used for testing LangChain integrations. ```python # echo.py from mcp.server.fastmcp import FastMCP from pydantic import Field # Create server mcp = FastMCP("Echo Server") @mcp.tool() def echo_tool(text: str = Field(description="The text to echo")) -> str: """Echo the input text Args: text (str): The text to echo Returns: str: The echoed text """ return text mcp.run() ``` -------------------------------- ### Low-Level Async Context Manager with mcptools Source: https://context7.com/grll/mcpadapt/llms.txt Shows how to use the `mcptools` async context manager for direct access to the MCP session and tools. This is suitable when you need to interact with the underlying session object for advanced use cases. ```python import asyncio from mcp import StdioServerParameters from mcp.types import CallToolResult from mcpadapt.core import mcptools async def main(): async with mcptools( StdioServerParameters(command="uv", args=["run", "src/echo.py"]), client_session_timeout_seconds=10, ) as (session, tools): print([t.name for t in tools]) # Call a tool directly on the session result: CallToolResult = await session.call_tool( "echo_tool", {"text": "hello world"} ) print(result.content[0].text) # → "hello world" asyncio.run(main()) ``` -------------------------------- ### Interact with Echo Server using LangChain Source: https://github.com/grll/mcpadapt/blob/main/docs/guide/langchain.md Demonstrates how to use LangChain's create_react_agent to interact with the MCPAdapt echo server. Ensure ANTHROPIC_API_KEY is set. ```python import os from langchain_anthropic import ChatAnthropic from langchain_core.messages import HumanMessage from langgraph.checkpoint.memory import MemorySaver from langgraph.prebuilt import create_react_agent from mcp import StdioServerParameters from mcpadapt.core import MCPAdapt from mcpadapt.langchain_adapter import LangChainAdapter # Initialize MCPAdapt with LangChain adapter async with MCPAdapt( StdioServerParameters(command="uv", args=["run", "echo.py"]), LangChainAdapter(), ) as tools: # Create the agent memory = MemorySaver() model = ChatAnthropic( model_name="claude-3-5-sonnet-20241022", max_tokens_to_sample=8192 ) agent_executor = create_react_agent(model, tools, checkpointer=memory) # Use the agent config = {"configurable": {"thread_id": "abc123"}} async for event in agent_executor.astream( { "messages": [ HumanMessage(content="Echo 'Hello, World!'") ] }, config, ): print(event) print("----") ``` -------------------------------- ### Define Dummy Tool Adapter Source: https://github.com/grll/mcpadapt/blob/main/examples/notebook_usage.ipynb A dummy tool adapter implementation for adapting functions to MCP's expected interface. Use this when you need a placeholder or custom adaptation logic. ```python # define a dummy tool adapter that just returns the function for the example. class DummyToolAdapter(ToolAdapter): def adapt( self, func: Callable[[dict | None], mcp.types.CallToolResult], mcp_tool: mcp.types.Tool, ): return func def async_adapt( self, afunc: Callable[[dict | None], Coroutine[Any, Any, mcp.types.CallToolResult]], mcp_tool: mcp.types.Tool, ): return afunc ``` -------------------------------- ### MCPAdapt Synchronous Context Manager Source: https://context7.com/grll/mcpadapt/llms.txt Use MCPAdapt as a synchronous context manager to launch an MCP server in a daemon thread. It adapts tools and yields them as a list of smolagents.Tool objects. Adjust connect_timeout for server readiness. ```python import os from mcp import StdioServerParameters from mcpadapt.core import MCPAdapt from mcpadapt.smolagents_adapter import SmolAgentsAdapter # Launch a public MCP server via uvx and get smolagents-compatible tools with MCPAdapt( StdioServerParameters( command="uvx", args=["--quiet", "pubmedmcp@0.1.3"], env={"UV_PYTHON": "3.12", **os.environ}, ), SmolAgentsAdapter(), connect_timeout=30, client_session_timeout_seconds=5, ) as tools: # tools is a plain list of smolagents.Tool objects print(tools[0].name) # e.g. "search_pubmed" print(tools[0].description) print(tools[0].inputs) # Call the tool directly result = tools[0](request={"term": "efficient treatment hangover"}) print(result) ``` -------------------------------- ### Use Airbnb MCP Server with Google GenAI Source: https://github.com/grll/mcpadapt/blob/main/docs/guide/google-genai.md Integrate Google GenAI with the Airbnb MCP server for real-world applications like booking. Requires GEMINI_API_KEY environment variable. ```python import os from google import genai from google.genai import types from mcp import StdioServerParameters from mcpadapt.core import MCPAdapt from mcpadapt.google_genai_adapter import GoogleGenAIAdapter # Initialize Google GenAI client client = genai.Client(api_key=os.getenv("GEMINI_API_KEY")) # Create server parameters for Airbnb MCP server_params = StdioServerParameters( command="npx", args=[ "-y", "@openbnb/mcp-server-airbnb", "--ignore-robots-txt", ], ) async def run(): async with MCPAdapt( server_params, GoogleGenAIAdapter(), ) as adapted_tools: # Unpack tools and tool_functions google_tools, tool_functions = zip(*adapted_tools) tool_functions = dict(tool_functions) prompt = "I want to book an apartment in Paris for 2 nights, March 28-30" # Generate content with function declarations response = client.models.generate_content( model="gemini-2.0-flash", contents=prompt, config=types.GenerateContentConfig( temperature=0.7, tools=google_tools, ), ) # Handle the function call if response.candidates[0].content.parts[0].function_call: function_call = response.candidates[0].content.parts[0].function_call result = await tool_functions[function_call.name](function_call.args) print(result.content[0].text) else: print("No function call found in the response.") print(response.text) if __name__ == "__main__": import asyncio asyncio.run(run()) ``` -------------------------------- ### Integrate Multiple MCP Servers with MCPAdapt Source: https://github.com/grll/mcpadapt/blob/main/README.md Adapt multiple MCP servers simultaneously by passing a list of server parameters to MCPAdapt. This aggregates tools from all specified servers into a single collection. ```python from mcp import StdioServerParameters from mcpadapt.core import MCPAdapt from mcpadapt.smolagents_adapter import SmolAgentsAdapter with MCPAdapt( [ StdioServerParameters(command="uv", args=["run", "src/echo1.py"]), StdioServerParameters(command="uv", args=["run", "src/echo2.py"]), ], SmolAgentsAdapter(), ) as tools: # tools is now a flattened list of tools from the 2 MCP servers. ... ``` -------------------------------- ### Standard IO (stdio) Usage with MCPAdapt (Synchronous) Source: https://github.com/grll/mcpadapt/blob/main/docs/quickstart.md Use MCPAdapt with StdioServerParameters for synchronous operations. MCPAdapt launches the MCP server in a subprocess and handles communication. ```python from mcp import StdioServerParameters from mcpadapt.core import MCPAdapt from mcpadapt._adapter import Adapter with MCPAdapt( StdioServerParameters(command="uv", args=["run", "src/echo.py"]), Adapter(), ) as tools: # tools is a list of tools 100% compatible with your agentic framework. ... ``` -------------------------------- ### Multiple MCP Servers Configuration with MCPAdapt Source: https://github.com/grll/mcpadapt/blob/main/docs/quickstart.md Configure MCPAdapt to connect to multiple MCP servers by providing a list of server parameters. This flattens the tools from all servers into a single list. ```python from mcp import StdioServerParameters from mcpadapt.core import MCPAdapt from mcpadapt._adapter import Adapter with MCPAdapt( [ StdioServerParameters(command="uv", args=["run", "src/echo1.py"]), StdioServerParameters(command="uv", args=["run", "src/echo2.py"]), ], Adapter(), ) as tools: # tools is now a flattened list of tools from the 2 MCP servers. ... ``` -------------------------------- ### Interact with Echo Server using Google GenAI Source: https://github.com/grll/mcpadapt/blob/main/docs/guide/google-genai.md Use the GoogleGenAIAdapter to connect to and interact with the echo server. Requires GEMINI_API_KEY environment variable. ```python import os from google import genai from google.genai import types from mcp import StdioServerParameters from mcpadapt.core import MCPAdapt from mcpadapt.google_genai_adapter import GoogleGenAIAdapter # Initialize Google GenAI client client = genai.Client(api_key=os.getenv("GEMINI_API_KEY")) # Create server parameters server_params = StdioServerParameters( command="uv", args=["run", "echo.py"] ) async def run(): async with MCPAdapt( server_params, GoogleGenAIAdapter(), ) as adapted_tools: # Unpack tools and tool_functions google_tools, tool_functions = zip(*adapted_tools) tool_functions = dict(tool_functions) prompt = "Please echo back 'Hello, World!'" # Generate content with function declarations response = client.models.generate_content( model="gemini-2.0-flash", contents=prompt, config=types.GenerateContentConfig( temperature=0.7, tools=google_tools, ), ) # Handle the function call if response.candidates[0].content.parts[0].function_call: function_call = response.candidates[0].content.parts[0].function_call result = await tool_functions[function_call.name](function_call.args) print(result.content[0].text) else: print("No function call found in the response.") print(response.text) if __name__ == "__main__": import asyncio asyncio.run(run()) ``` -------------------------------- ### Use PubMed MCP Server with Smolagents Source: https://github.com/grll/mcpadapt/blob/main/docs/guide/smolagents.md Integrate with a pre-built PubMed MCP server to find studies. Use the `--quiet` flag with `uvx` to prevent output interference. Consider security implications when including `os.environ`. ```python import os from mcp import StdioServerParameters from smolagents import CodeAgent, HfApiModel # type: ignore from smolagents.tools import ToolCollection with ToolCollection.from_mcp( StdioServerParameters( command="uvx", args=["--quiet", "pubmedmcp@0.1.3"], env={"UV_PYTHON": "3.12", **os.environ}, ), ) as tools: # print(tools[0](request={"term": "efficient treatment hangover"})) agent = CodeAgent(tools=tools, model=HfApiModel()) agent.run("Find studies about hangover?") ``` -------------------------------- ### LangChain ReAct Agent with MCP Tools Source: https://context7.com/grll/mcpadapt/llms.txt Integrates MCP tools with LangChain's create_react_agent for use in ReAct agents. Requires LangChain and MCP dependencies. Ensure environment variables like GEMINI_API_KEY are set if needed. ```python import asyncio, os from dotenv import load_dotenv from langchain_anthropic import ChatAnthropic from langchain_core.messages import HumanMessage from langgraph.checkpoint.memory import MemorySaver from langgraph.prebuilt import create_react_agent from mcp import StdioServerParameters from mcpadapt.core import MCPAdapt from mcpadapt.langchain_adapter import LangChainAdapter load_dotenv() async def main(): async with MCPAdapt( StdioServerParameters( command="uvx", args=["--quiet", "pubmedmcp@0.1.3"], env={"UV_PYTHON": "3.12", **os.environ}, ), LangChainAdapter(), ) as tools: model = ChatAnthropic( model_name="claude-3-5-sonnet-20241022", max_tokens_to_sample=8192 ) agent = create_react_agent(model, tools, checkpointer=MemorySaver()) config = {"configurable": {"thread_id": "session-1"}} async for event in agent.astream( {"messages": [HumanMessage(content="Find studies on hangover treatment.")]}, config, ): print(event) asyncio.run(main()) ``` -------------------------------- ### Standard IO (stdio) Usage with MCPAdapt (Asynchronous) Source: https://github.com/grll/mcpadapt/blob/main/docs/quickstart.md Use MCPAdapt with StdioServerParameters for asynchronous operations. This is suitable when your agentic framework supports async. ```python from mcp import StdioServerParameters from mcpadapt.core import MCPAdapt from mcpadapt._adapter import Adapter async with MCPAdapt( StdioServerParameters(command="uv", args=["run", "src/echo.py"]), Adapter(), ) as tools: # tools is a list of tools 100% compatible with your agentic framework. ... ``` -------------------------------- ### Integrate MCP Tools with SmolAgentsAdapter Source: https://context7.com/grll/mcpadapt/llms.txt Demonstrates using `SmolAgentsAdapter` to convert MCP tools into `smolagents.Tool` subclasses, supporting various content types. Set `structured_output=True` for `outputSchema` and `structuredContent` support (MCP spec 2025-06-18+). ```python import os from mcp import StdioServerParameters from smolagents import CodeAgent, HfApiModel from mcpadapt.core import MCPAdapt from mcpadapt.smolagents_adapter import SmolAgentsAdapter with MCPAdapt( StdioServerParameters( command="uvx", args=["--quiet", "pubmedmcp@0.1.3"], env={"UV_PYTHON": "3.12", **os.environ}, ), SmolAgentsAdapter(structured_output=False), # set True for outputSchema support ) as tools: # Use tools standalone print(tools[0](request={"term": "hangover treatment"})) # Or hand them to a CodeAgent agent = CodeAgent(tools=tools, model=HfApiModel()) agent.run("Find studies about the treatment of hangovers.") ``` -------------------------------- ### Interact with Echo Server using CrewAI Source: https://github.com/grll/mcpadapt/blob/main/docs/guide/crewai.md Set up a CrewAI agent and task to interact with the echo server. The MCPAdapt is initialized to connect to the server, and the echo tool is provided to the agent. ```python import os from crewai import Agent, Crew, Task from mcp import StdioServerParameters from mcpadapt.core import MCPAdapt from mcpadapt.crewai_adapter import CrewAIAdapter with MCPAdapt( StdioServerParameters(command="uv", args=["run", "echo.py"]), CrewAIAdapter(), ) as tools: # Create an echo agent agent = Agent( role="Echo Agent", goal="Echo messages back to the user", backstory="You help echo messages back to users", verbose=True, tools=[tools[0]], ) # Create a task task = Task( description="Echo 'Hello, World!'", agent=agent, expected_output="The echoed message", ) # Create and run the crew crew = Crew(agents=[agent], tasks=[task], verbose=True) crew.kickoff() ``` -------------------------------- ### Use MCP Server with Smolagents Source: https://github.com/grll/mcpadapt/blob/main/README.md Integrate an MCP server into smolagents using ToolCollection.from_mcp. Ensure the server parameters are correctly defined. ```python from mcp import StdioServerParameters from smolagents.tools import ToolCollection serverparams = StdioServerParameters(command="uv", args=["run", "src/echo.py"]) with ToolCollection.from_mcp(serverparams) as tool_collection: ... # enjoy your tools! ``` -------------------------------- ### Use PubMed MCP Server with LangChain Source: https://github.com/grll/mcpadapt/blob/main/docs/guide/langchain.md Shows how to integrate LangChain with a community-provided PubMed MCP server. Requires ANTHROPIC_API_KEY and uses uvx command. Use --quiet flag for uvx. ```python import os from dotenv import load_dotenv from langchain_anthropic import ChatAnthropic from langchain_core.messages import HumanMessage from langgraph.checkpoint.memory import MemorySaver from langgraph.prebuilt import create_react_agent from mcp import StdioServerParameters from mcpadapt.core import MCPAdapt from mcpadapt.langchain_adapter import LangChainAdapter # Load environment variables load_dotenv() if not os.environ.get("ANTHROPIC_API_KEY"): raise ValueError("ANTHROPIC_API_KEY must be set in your environment variables") async with MCPAdapt( StdioServerParameters( command="uvx", args=["--quiet", "pubmedmcp@0.1.3"], env={"UV_PYTHON": "3.12", **os.environ}, ), LangChainAdapter(), ) as tools: # Create the agent memory = MemorySaver() model = ChatAnthropic( model_name="claude-3-5-sonnet-20241022", max_tokens_to_sample=8192 ) agent_executor = create_react_agent(model, tools, checkpointer=memory) # Use the agent config = {"configurable": {"thread_id": "abc123"}} async for event in agent_executor.astream( { "messages": [ HumanMessage( content="Find relevant studies on alcohol hangover and treatment." ) ] }, config, ): print(event) print("----") ``` -------------------------------- ### Interact with the Echo Server using Smolagents Source: https://github.com/grll/mcpadapt/blob/main/docs/guide/smolagents.md Connect to and interact with the created echo server using Smolagents CodeAgent. Ensure the server is running before executing this code. ```python from mcp import StdioServerParameters from smolagents import CodeAgent, HfApiModel # type: ignore from smolagents.tools import ToolCollection serverparams = StdioServerParameters(command="uv", args=["run", "echo.py"]) with ToolCollection.from_mcp(serverparams) as tool_collection: agent = CodeAgent(tools=tools, model=HfApiModel()) agent.run("Can you echo something?") ``` -------------------------------- ### MCPAdapt Asynchronous Context Manager Source: https://context7.com/grll/mcpadapt/llms.txt Utilize MCPAdapt as an async context manager for frameworks supporting async tools, like LangChain. It runs within the caller's event loop and returns async-compatible tools. ```python import asyncio from mcp import StdioServerParameters from mcpadapt.core import MCPAdapt from mcpadapt.langchain_adapter import LangChainAdapter async def main(): async with MCPAdapt( StdioServerParameters( command="uvx", args=["--quiet", "pubmedmcp@0.1.3"], ), LangChainAdapter(), ) as tools: # tools is a list of LangChain BaseTool objects with async support result = await tools[0].ainvoke({"term": "hangover treatment"}) print(result) asyncio.run(main()) ``` -------------------------------- ### SSE (Server-Sent Events) Usage with MCPAdapt (Asynchronous) Source: https://github.com/grll/mcpadapt/blob/main/docs/quickstart.md Configure MCPAdapt to use SSE by providing a dictionary with the SSE endpoint URL and optional parameters. This supports asynchronous operations. ```python from mcpadapt.core import MCPAdapt from mcpadapt._adapter import Adapter async with MCPAdapt( { "url": "http://127.0.0.1:8000/sse", # Optional parameters: # "headers": {"Authorization": "Bearer token"}, # "timeout": 5, # Connection timeout in seconds # "sse_read_timeout": 300 # SSE read timeout in seconds (default: 5 minutes) }, Adapter() ) as tools: # 'tools' contains framework-compatible tools ... ``` -------------------------------- ### Use MCPAdapt Smolagents Adapter with PubMed MCP Server Source: https://github.com/grll/mcpadapt/blob/main/docs/guide/smolagents.md Utilize the MCPAdapt smolagents adapter to interact with the PubMed MCP server. This approach achieves the same result as direct integration but uses MCPAdapt directly. ```python import os from mcp import StdioServerParameters from smolagents import CodeAgent, HfApiModel # type: ignore from mcpadapt.core import MCPAdapt from mcpadapt.smolagents_adapter import SmolAgentsAdapter with MCPAdapt( StdioServerParameters( command="uvx", args=["--quiet", "pubmedmcp@0.1.3"], env={"UV_PYTHON": "3.12", **os.environ}, ), SmolAgentsAdapter(), ) as tools: agent = CodeAgent(tools=tools, model=HfApiModel()) agent.run("Find studies about hangover?") ``` -------------------------------- ### MCPAdapt SSE/Streamable-HTTP Transport Source: https://context7.com/grll/mcpadapt/llms.txt Connect to a remote MCP server by providing a dictionary with a 'url' key instead of StdioServerParameters. Use the 'transport' key to specify the protocol (e.g., 'sse', 'streamable-http', 'ws'). ```python import subprocess, time from mcpadapt.core import MCPAdapt from mcpadapt.smolagents_adapter import SmolAgentsAdapter ``` -------------------------------- ### Generate Pydantic Models from JSON Schema in Python Source: https://context7.com/grll/mcpadapt/llms.txt Use create_model_from_json_schema to convert an MCP tool's JSON Schema inputSchema into a typed Pydantic BaseModel. This utility handles complex schema features like $ref, nested objects, and arrays. ```python from mcpadapt.utils.modeling import create_model_from_json_schema, resolve_refs_and_remove_defs raw_schema = { "type": "object", "properties": { "query": {"type": "string", "description": "Search query"}, "max_results": {"type": "integer", "description": "Max number of results", "default": 10}, "filters": { "type": "object", "properties": { "year_from": {"type": "integer"}, "year_to": {"type": "integer"}, }, }, }, "required": ["query"], } # Resolve any $ref / $defs before creating the model clean_schema = resolve_refs_and_remove_defs(raw_schema) SearchInput = create_model_from_json_schema(clean_schema, model_name="SearchInput") # Validate and use like any Pydantic model instance = SearchInput(query="hangover treatment", max_results=5) print(instance.model_dump()) # → {'query': 'hangover treatment', 'max_results': 5, 'filters': None} # Required field missing → raises ValidationError try: SearchInput(max_results=3) except Exception as e: print(e) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.