examples/langraph.py.
Objective
Create an agent that can answer questions like “What is 2 + 2?”.Steps
-
Define the Calculator Tool:
First, we define a simple Python function that will perform the calculation. This function will be our custom tool.
Note the type hints and docstring, which Universal MCP will use to generate metadata for the tool.
-
Set up LLM and ToolManager:
Initialize your preferred LLM (e.g.,
ChatOpenAI) and theToolManager. -
Register the Calculator Tool:
Add the
calculatefunction to theToolManager. -
Get Tools in Langchain Format:
Retrieve the list of tools in a format compatible with Langchain.
-
Create the Langchain Agent:
We’ll use the
create_react_agentfromlanggraph.prebuilt. -
Invoke the Agent:
Now, you can ask the agent a question that requires calculation.
How It Works
- The user asks “What is 2 + 2?”.
- The Langchain ReAct agent, prompted to use tools, identifies that the “calculate” tool (whose description was generated from its docstring) is suitable.
- It invokes the “calculate” tool with the argument
s="2 + 2". - The
calculatefunction (managed by Universal MCP’sToolwrapper) executes and returns4. - The agent receives the result and formulates the final answer, e.g., “The result is 4.”
Applications.