View the source code for this module on GitHub: https://github.com/mcp-use/mcp-use/blob/main/libraries/python/mcp_use/agents/mcpagent.py
- The agent uses create_agent() from langchain.agents which returns a CompiledStateGraph
- New methods: astream_simplified() and run_v2() leverage the built-in astream() from CompiledStateGraph which handles the agent loop internally
- Legacy methods: stream() and run() use manual step-by-step execution for backward compatibility
MCPAgent
from mcp_use.agents.mcpagent import MCPAgent
method init
Initialize a new MCPAgent instance.ParametersSignaturelangchain_core.language_models.base.BaseLanguageModel | Nonedefault:"None"The LangChain LLM to use. Not required if agent_id is provided for remote execution.mcp_use.client.client.MCPClient | Nonedefault:"None"The MCPClient to use. If provided, connector is ignored.list[mcp_use.client.connectors.base.BaseConnector] | Nonedefault:"None"A list of MCP connectors to use if client is not provided.intdefault:"5"The maximum number of steps to take.booldefault:"False"Whether to automatically initialize the agent when run is called.booldefault:"True"Whether to maintain conversation history for context.str | Nonedefault:"None"Complete system prompt to use (overrides template if provided).str | Nonedefault:"None"Template for system prompt with placeholder.str | Nonedefault:"None"Extra instructions to append to the system prompt.list[str] | Nonedefault:"None"List of tool names that should not be available to the agent.list[str] | Nonedefault:"None"List of toolsbooldefault:"False"Whether to use server manager mode instead of exposing all tools.mcp_use.agents.managers.base.BaseServerManager | Nonedefault:"None"Server name or configurationbooldefault:"False"Enable debug/verbose modebooldefault:"False"Whether to pretty print the output.str | Nonedefault:"None"Remote agent ID for remote execution. If provided, creates a remote agent.str | Nonedefault:"None"API key for remote execution. If None, checks MCP_USE_API_KEY env var.strdefault:"https://cloud.manufact.com"Base URL for remote API calls.list | Nonedefault:"None"List of LangChain callbacks to use. If None and Langfuse is configured, uses langfuse_handler.str | Nonedefault:"None"String valuebooldefault:"True"Whether to enable automatic error handling for tool calls. When True, tool errors
def __init__(llm: langchain_core.language_models.base.BaseLanguageModel | None = None, client: mcp_use.client.client.MCPClient | None = None, connectors: list[mcp_use.client.connectors.base.BaseConnector] | None = None, max_steps: int = 5, auto_initialize: bool = False, memory_enabled: bool = True, system_prompt: str | None = None, system_prompt_template: str | None = None, additional_instructions: str | None = None, disallowed_tools: list[str] | None = None, tools_used_names: list[str] | None = None, use_server_manager: bool = False, server_manager: mcp_use.agents.managers.base.BaseServerManager | None = None, verbose: bool = False, pretty_print: bool = False, agent_id: str | None = None, api_key: str | None = None, base_url: str = "https://cloud.manufact.com", callbacks: list | None = None, chat_id: str | None = None, retry_on_error: bool = True):
method clear_conversation_history
Clear the conversation history.Signaturedef clear_conversation_history():
method run
Run a query using LangChain 1.0.0’s agent and return the final result.Example:# Regular usage
result = await agent.run("What's the weather like?")
# Structured output usage
from pydantic import BaseModel, Field
class WeatherInfo(BaseModel):
temperature: float = Field(description="Temperature in Celsius")
condition: str = Field(description="Weather condition")
weather: WeatherInfo = await agent.run(
"What's the weather like?",
output_schema=WeatherInfo
)
Returnsstr | langchain_core.messages.human.HumanMessagerequiredThe query to run. Accepts a plain string or aHumanMessagewhenint | Nonedefault:"None"Optional maximum number of steps to take.booldefault:"True"Whether to handle the connector lifecycle internally.list[langchain_core.messages.base.BaseMessage] | Nonedefault:"None"Optional external history to use instead of thetype[~T] | Nonedefault:"None"Optional Pydantic BaseModel class for structured output.
Signaturestr | mcp_use.agents.mcpagent.TThe result of running the query as a string, or if output_schema is provided, an instance of the specified Pydantic model.
def run(
query: str | langchain_core.messages.human.HumanMessage,
max_steps: int | None = None,
manage_connector: bool = True,
external_history: list[langchain_core.messages.base.BaseMessage] | None = None,
output_schema: type[~T] | None = None
):
method stream
Async generator using LangChain 1.0.0’s create_agent and astream.This method leverages the LangChain 1.0.0 API where create_agent returns
a CompiledStateGraph that handles the agent loop internally via astream.Tool Updates with Server Manager:
When using server_manager mode, this method handles dynamic tool updates:- Before execution: Updates are applied immediately to the new stream
- During execution: When tools change, we wait for a “safe restart point” (after tool results complete), then interrupt the stream, recreate the agent with new tools, and resume execution with accumulated messages.
- Safe restart points: Only restart after tool results to ensure message pairs (tool_use + tool_result) are complete, satisfying LLM API requirements.
- Max restarts: Limited to 3 restarts to prevent infinite loops
Returnsstr | langchain_core.messages.human.HumanMessagerequiredThe query to run. Accepts a plain string or aHumanMessagewhenint | Nonedefault:"None"Integer valuebooldefault:"True"Whether to handle the connector lifecycle internally.list[langchain_core.messages.base.BaseMessage] | Nonedefault:"None"Optional external history to use instead of thebooldefault:"True"Boolean flagtype[~T] | Nonedefault:"None"Optional Pydantic BaseModel class for structured output.
SignatureAsyncGenerator
def stream(
query: str | langchain_core.messages.human.HumanMessage,
max_steps: int | None = None,
manage_connector: bool = True,
external_history: list[langchain_core.messages.base.BaseMessage] | None = None,
track_execution: bool = True,
output_schema: type[~T] | None = None
):
method stream_events
Asynchronous streaming interface.Example::async for chunk in agent.stream_events(“hello”):
print(chunk)ParametersReturnsstr | langchain_core.messages.human.HumanMessagerequiredQuery string or inputint | Nonedefault:"None"Integer valuebooldefault:"True"Connector instancelist[langchain_core.messages.base.BaseMessage] | Nonedefault:"None"List of items
SignatureAsyncIterator
def stream_events(
query: str | langchain_core.messages.human.HumanMessage,
max_steps: int | None = None,
manage_connector: bool = True,
external_history: list[langchain_core.messages.base.BaseMessage] | None = None
):