Skip to main content

Prerequisites

Before we begin, you’ll need OpenAI API key and Klavis API key.

Installation

First, install the required packages:
pip install langchain-mcp-adapters langgraph langchain-openai klavis
npm install @langchain/mcp-adapters langchain @langchain/openai klavis open dotenv

Setup Environment Variables

import os

os.environ["OPENAI_API_KEY"] = "YOUR_OPENAI_API_KEY"  # Replace
os.environ["KLAVIS_API_KEY"] = "YOUR_KLAVIS_API_KEY"  # Replace
import { config } from 'dotenv';

// Load environment variables from .env file
config();

// Make sure you have a .env file with:
// OPENAI_API_KEY=your_openai_api_key
// KLAVIS_API_KEY=your_klavis_api_key

Step 1 - Create Strata MCP Server with Gmail and Slack

from klavis import Klavis
from klavis.types import McpServerName, ToolFormat
import webbrowser

klavis_client = Klavis(api_key=os.getenv("KLAVIS_API_KEY"))

response = klavis_client.mcp_server.create_strata_server(
    servers=[McpServerName.GMAIL, McpServerName.SLACK], 
    user_id="1234"
)

# Handle OAuth authorization for each services
if response.oauth_urls:
    for server_name, oauth_url in response.oauth_urls.items():
        webbrowser.open(oauth_url)
        print(f"Or please open this URL to complete {server_name} OAuth authorization: {oauth_url}")
import { KlavisClient, Klavis } from 'klavis';
import open from 'open';
import { createInterface } from 'readline/promises';

const klavisClient = new KlavisClient({ apiKey: process.env.KLAVIS_API_KEY });

const response = await klavisClient.mcpServer.createStrataServer({
    servers: [Klavis.McpServerName.Gmail, Klavis.McpServerName.Slack],
    userId: "1234"
});

// Handle OAuth authorization for each service
if (response.oauthUrls) {
    const rl = createInterface({
        input: process.stdin,
        output: process.stdout,
    });

    for (const [serverName, oauthUrl] of Object.entries(response.oauthUrls)) {
        await open(oauthUrl);
        await rl.question(`Press Enter after completing ${serverName} OAuth authorization...`);
    }
    
    rl.close();
}
OAuth Authorization Required: The code above will open browser windows for each service. Click through the OAuth flow to authorize access to your accounts.

Step 2 - Create LangChain Agent with Strata MCP Server

import asyncio
from langchain_mcp_adapters.client import MultiServerMCPClient
from langgraph.prebuilt import create_react_agent
from langchain_openai import ChatOpenAI

# Initialize LLM
llm = ChatOpenAI(model="gpt-4o-mini", api_key=os.getenv("OPENAI_API_KEY"))

# Create MCP client with Strata server
mcp_client = MultiServerMCPClient({
    "strata": {
        "transport": "streamable_http",
        "url": response.strata_server_url
    }
})

# Get tools from Strata MCP server
tools = asyncio.run(mcp_client.get_tools())

# Create agent with MCP-based tools
agent = create_react_agent(
    model=llm,
    tools=tools,
    prompt="You are a helpful assistant that uses MCP tools to interact with Gmail and Slack."
)

print("🤖 LangChain agent created successfully!")
import { MultiServerMCPClient } from "@langchain/mcp-adapters";
import { createAgent } from "langchain";
import { ChatOpenAI } from "@langchain/openai";

// Initialize LLM
const llm = new ChatOpenAI({
    modelName: "gpt-4o-mini",
    apiKey: process.env.OPENAI_API_KEY
});

// Create MCP client with Strata server
const mcpClient = new MultiServerMCPClient({
    throwOnLoadError: true,
    useStandardContentBlocks: true,
    mcpServers: {
        strata: {
            url: response.strataServerUrl,
            transport: "http"
        }
    }
});

// Get tools from Strata MCP server
const tools = await mcpClient.getTools();

// Create agent with MCP-based tools
const agent = createAgent({
    model: llm,
    tools: tools,
    systemPrompt: "You are a helpful assistant that uses MCP tools to interact with Gmail and Slack."
});

console.log("🤖 LangChain agent created successfully!");

Step 3 - Run!

response_message = asyncio.run(agent.ainvoke({
    "messages": [{"role": "user", "content": "Check my latest 5 emails and summarize them in a Slack message to #general"}]
}))

print(f"\n🤖 Final Response: {response_message['messages'][-1].content}")
const result = await agent.invoke({
    messages: [{
        role: 'user' as const,
        content: 'Check my latest 5 emails and summarize them in a Slack message to #general'
    }]
});

// Print only the final AI response content
const lastMessage = result.messages[result.messages.length - 1];
console.log('\n🤖 Final Response:', lastMessage.content);
Check out the full TypeScript code example on GitHub for a complete working implementation.
Perfect! You’ve integrated LangChain with Klavis MCP servers.

Next Steps

Integrations

Explore available MCP servers

API Reference

REST endpoints and schemas

Useful Resources

Happy building 🚀