MetorialDocs

Add Metorial tools to a LangChain or LangGraph agent

Connect with the metorialLangchain adapter in TypeScript or metorial_langchain in Python, then pass session.tools() to createAgent, create_agent or a ToolNode.

This guide takes you from an empty folder to a LangChain agent that searches the web through Metorial. Connect with the LangChain adapter (metorialLangchain() in TypeScript, metorial_langchain() in Python) and pass session.tools() to createAgent or create_agent. For a LangGraph graph, give the same tools to a ToolNode.

What you'll learn

  • How to create an API key and a provider deployment from the CLI
  • How to pass Metorial tools to a LangChain agent in TypeScript and Python
  • How to use the same tools in a LangGraph StateGraph

Before you start

Set up Metorial with the CLI

Find your instance

An instance is one environment of a project. List yours and note the ID of the one the agent should use:

metorial-admin instance list

Create an API key

metorial-admin api-keys create \
  --type instance_access_token_secret \
  --instance-id <instance-id> \
  --name my-agent

Copy the secret from the output. It starts with metorial_sk_ and is shown only once.

Deploy a provider

Metorial Search is a built-in web search provider that needs no credentials.

metorial-admin providers deployments create \
  --provider-id metorial-search \
  --name "Metorial Search"

Copy the deployment ID from the output. It starts with pde_.

Export the values

export METORIAL_API_KEY="metorial_sk_..."
export METORIAL_PROVIDER_DEPLOYMENT_ID="pde_..."
export ANTHROPIC_API_KEY="sk-ant-..."

Build a LangChain agent

Create the project

mkdir my-agent && cd my-agent
npm init -y
npm pkg set type=module
npm install metorial @metorial/langchain langchain @langchain/core @langchain/anthropic
npm install --save-dev tsx
mkdir my-agent && cd my-agent
python3 -m venv .venv
source .venv/bin/activate
pip install metorial langchain langchain-anthropic langgraph

Write the agent

Save this as agent.ts or agent.py.

import { metorialLangchain } from '@metorial/langchain';
import { createAgent } from 'langchain';
import Metorial from 'metorial';

let metorial = new Metorial({ apiKey: process.env.METORIAL_API_KEY! });

let session = await metorial.connect({
  adapter: metorialLangchain(),
  providers: [{ providerDeploymentId: process.env.METORIAL_PROVIDER_DEPLOYMENT_ID! }]
});

let tools = session.tools();
console.log('Metorial tools:', tools.map(tool => tool.name).join(', '));

let agent = createAgent({ model: 'anthropic:claude-sonnet-5', tools });

let result = await agent.invoke({
  messages: [
    {
      role: 'user',
      content:
        'Search the web for the latest news about AI agents and summarize the top 3 stories.'
    }
  ]
});

console.log(result.messages.at(-1)?.content);
import asyncio
import os

from langchain.agents import create_agent
from metorial import Metorial, metorial_langchain


async def main():
    metorial = Metorial(api_key=os.environ["METORIAL_API_KEY"])

    session = await metorial.connect(
        adapter=metorial_langchain(),
        providers=[
            {"provider_deployment_id": os.environ["METORIAL_PROVIDER_DEPLOYMENT_ID"]}
        ],
    )

    tools = session.tools()
    print("Metorial tools:", ", ".join(tool.name for tool in tools))

    agent = create_agent("anthropic:claude-sonnet-5", tools=tools)

    result = await agent.ainvoke(
        {
            "messages": [
                {
                    "role": "user",
                    "content": "Search the web for the latest news about AI agents and summarize the top 3 stories.",
                }
            ]
        }
    )
    print(result["messages"][-1].content)


asyncio.run(main())

Run it

npx tsx agent.ts
python agent.py

Use the tools in a LangGraph graph

metorial_langgraph() returns the same LangChain tools. Bind them to the model and give them to a ToolNode. Save this as graph.py in the same project and run python graph.py.

import asyncio
import os

from langchain.chat_models import init_chat_model
from langchain.messages import HumanMessage
from langgraph.graph import START, MessagesState, StateGraph
from langgraph.prebuilt import ToolNode, tools_condition
from metorial import Metorial, metorial_langgraph


async def main():
    metorial = Metorial(api_key=os.environ["METORIAL_API_KEY"])

    session = await metorial.connect(
        adapter=metorial_langgraph(),
        providers=[
            {"provider_deployment_id": os.environ["METORIAL_PROVIDER_DEPLOYMENT_ID"]}
        ],
    )
    tools = session.tools()

    model = init_chat_model("anthropic:claude-sonnet-5").bind_tools(tools)

    async def call_model(state: MessagesState):
        return {"messages": [await model.ainvoke(state["messages"])]}

    builder = StateGraph(MessagesState)
    builder.add_node("model", call_model)
    builder.add_node("tools", ToolNode(tools))
    builder.add_edge(START, "model")
    builder.add_conditional_edges("model", tools_condition)
    builder.add_edge("tools", "model")
    graph = builder.compile()

    result = await graph.ainvoke(
        {"messages": [HumanMessage("Search the web for the latest news about AI agents.")]}
    )
    for message in result["messages"]:
        message.pretty_print()


asyncio.run(main())

Note

The Python tools are async only. Run the agent or graph with ainvoke or astream.

Check it worked

The agent prints the tool names, then its answer. Metorial prefixes each tool with the provider name and adds metorial_connection_status, a diagnostic tool, to every session. The graph prints every message, so you see the tool call and its result before the answer.

Metorial tools: metorial_connection_status, metorial_search_getWebContent, metorial_search_webSearch
<a summary of three news stories>

List the tool calls Metorial recorded for the deployment:

metorial-admin sessions tool-calls list \
  --provider-deployment-id $METORIAL_PROVIDER_DEPLOYMENT_ID \
  --limit 5

Use other apps and each user's own account

Find a provider and deploy it the same way, then add its deployment ID to providers. One session can hold several.

metorial-admin providers list --search hubspot
metorial-admin providers deployments create --provider-id <provider-id> --name "HubSpot"

Apps such as HubSpot need a sign-in. Pass the user's provider auth config next to the deployment ID, as providerAuthConfigId in TypeScript and provider_auth_config_id in Python. Let each user connect their own account shows how to get one for each user.

Troubleshooting

StructuredTool does not support sync invocation.

You called the Python agent or graph with invoke or stream. Use ainvoke or astream.

Invalid API key status=401

The Python SDK raises this AuthenticationError when the key is wrong. In TypeScript the message is [METORIAL ERROR]: unauthorized - Invalid API key. Check that METORIAL_API_KEY holds the full secret and belongs to the instance where you created the deployment.

ImportError: langchain-core is required for LangChain integration. Install it with: pip install langchain-core

The adapter could not import LangChain. Install langchain in the same virtual environment as metorial.

Provider requires an auth config to be provided

A provider deployment in the session needs a sign-in and got no provider auth config. Add the user's provider_auth_config_id to that entry.

Next steps