> Documentation index: https://metorial.com/llms.txt. Every page is available as Markdown by adding .md to its URL.

# Add Metorial tools to a LangChain or LangGraph agent
URL: https://metorial.com/docs/build/frameworks/langchain

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**

* [Install the CLI and sign in](https://metorial.com/docs/build/sandboxes#install-the-tools)
* An Anthropic API key
* Node.js 20 or later, or Python 3.10 or later

## Set up Metorial with the CLI

### 1. Find your instance

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

```bash
metorial-admin instance list
```

### 2. Create an API key

```bash
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.

### 3. Deploy a provider

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

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

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

### 4. Export the values

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

## Build a LangChain agent

### 1. Create the project

**TypeScript**

```bash
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
```

**Python**

```bash
mkdir my-agent && cd my-agent
python3 -m venv .venv
source .venv/bin/activate
pip install metorial langchain langchain-anthropic langgraph
```

### 2. Write the agent

Save this as `agent.ts` or `agent.py`.

**TypeScript**

```typescript
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);
```

**Python**

```python
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())
```

### 3. Run it

**TypeScript**

```bash
npx tsx agent.ts
```

**Python**

```bash
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`.

```python
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.

```text
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:

```bash
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.

```bash
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](https://metorial.com/docs/build/sdk/oauth) 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

* [Let each user connect their own account](https://metorial.com/docs/build/sdk/oauth): per-user OAuth for Slack, Gmail, GitHub and other apps
* [Limit the tools an agent can use](https://metorial.com/docs/build/guides/limit-agent-tools): serve only some of a provider's tools
* [Use tools from several apps in one session](https://metorial.com/docs/build/guides/use-tools-from-several-apps): one agent, several providers
* The official examples: `metorial-admin example create metorial-langchain-typescript-langchain` for TypeScript, `metorial-langchain-langchain` and `metorial-langgraph` for Python