# Claude Source: https://www.klavis.ai/docs/ai-platform-integration/claude Learn how to build AI agents that integrate Anthropic's Claude with Strata MCP servers to build AI agents that can interact with Gmail and Slack. [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/klavis-ai/klavis/blob/main/examples/claude/Use_Klavis_with_Claude.ipynb) ## Prerequisites Before we begin, you'll need: Get your API key from Anthropic Console Get your API key from Klavis AI ## Installation First, install the required packages: ```bash Python theme={null} pip install anthropic klavis ``` ```bash TypeScript theme={null} npm install @anthropic-ai/sdk klavis ``` ## Setup Environment Variables ```python Python theme={null} import os os.environ["ANTHROPIC_API_KEY"] = "YOUR_ANTHROPIC_API_KEY" # Replace with your actual Anthropic API key os.environ["KLAVIS_API_KEY"] = "YOUR_KLAVIS_API_KEY" # Replace with your actual Klavis API key ``` ```typescript TypeScript theme={null} import Anthropic from '@anthropic-ai/sdk'; import { KlavisClient, Klavis } from 'klavis'; // Set environment variables process.env.ANTHROPIC_API_KEY = "YOUR_ANTHROPIC_API_KEY"; // Replace with your actual Anthropic API key process.env.KLAVIS_API_KEY = "YOUR_KLAVIS_API_KEY"; // Replace with your actual Klavis API key ``` ### Step 1 - Create Strata MCP Server with Gmail and Slack ```python Python theme={null} 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}") ``` ```typescript TypeScript theme={null} 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 services if (response.oauthUrls) { for (const [serverName, oauthUrl] of Object.entries(response.oauthUrls)) { window.open(oauthUrl); // Wait for user to complete OAuth await new Promise(resolve => { const input = prompt(`Press OK after completing ${serverName} OAuth authorization...`); resolve(input); }); } } ``` **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 method to use MCP Server with Claude This method handles multiple rounds of tool calls until a final response is ready, allowing the AI to chain tool executions for complex tasks. ```python Python theme={null} import json from anthropic import Anthropic def claude_with_mcp_server(mcp_server_url: str, user_query: str): claude_client = Anthropic(api_key=os.getenv("ANTHROPIC_API_KEY")) messages = [ {"role": "user", "content": f"{user_query}"} ] mcp_server_tools = klavis_client.mcp_server.list_tools( server_url=mcp_server_url, format=ToolFormat.ANTHROPIC ) max_iterations = 10 iteration = 0 while iteration < max_iterations: iteration += 1 response = claude_client.messages.create( model="claude-sonnet-4-5-20250929", max_tokens=4000, system="You are a helpful assistant. Use the available tools to answer the user's question.", messages=messages, tools=mcp_server_tools.tools ) messages.append({"role": "assistant", "content": response.content}) if response.stop_reason == "tool_use": tool_results = [] for content_block in response.content: if content_block.type == "tool_use": function_name = content_block.name function_args = content_block.input print(f"šŸ”§ Calling: {function_name}, with args: {function_args}") result = klavis_client.mcp_server.call_tools( server_url=mcp_server_url, tool_name=function_name, tool_args=function_args ) tool_results.append({ "type": "tool_result", "tool_use_id": content_block.id, "content": str(result) }) messages.append({"role": "user", "content": tool_results}) continue else: return response.content[0].text return "Max iterations reached without final response" ``` ```typescript TypeScript theme={null} async function claudeWithMcpServer(mcpServerUrl: string, userQuery: string) { const claudeClient = new Anthropic({ apiKey: process.env.ANTHROPIC_API_KEY }); const messages = [ { role: "user", content: userQuery } ]; const mcpServerTools = await klavisClient.mcpServer.listTools({ serverUrl: mcpServerUrl, format: Klavis.ToolFormat.Anthropic }); const maxIterations = 10; let iteration = 0; while (iteration < maxIterations) { iteration++; const response = await claudeClient.messages.create({ model: "claude-sonnet-4-5-20250929", max_tokens: 4000, system: "You are a helpful assistant. Use the available tools to answer the user's question.", messages: messages, tools: mcpServerTools.tools }); messages.push({ role: "assistant", content: response.content }); if (response.stop_reason === "tool_use") { const toolResults = []; for (const contentBlock of response.content) { if (contentBlock.type === "tool_use") { const functionName = contentBlock.name; const functionArgs = contentBlock.input; console.log(`šŸ”§ Calling: ${functionName}, with args:`, functionArgs); const result = await klavisClient.mcpServer.callTools({ serverUrl: mcpServerUrl, toolName: functionName, toolArgs: functionArgs }); toolResults.push({ type: "tool_result", tool_use_id: contentBlock.id, content: JSON.stringify(result) }); } } messages.push({ role: "user", content: toolResults }); continue; } else { return response.content[0].text; } } return "Max iterations reached without final response"; } ``` ### Step 3 - Run! ```python Python theme={null} result = claude_with_mcp_server( mcp_server_url=response.strata_server_url, user_query="Check my latest 5 emails and summarize them in a Slack message to #general" ) print(f"\nšŸ¤– Final Response: {result}") ``` ```typescript TypeScript theme={null} result = await claudeWithMcpServer( response.strataServerUrl, "Check my latest emails and summarize them in a Slack message to #updates" ); console.log(`\nšŸ¤– Final Response: ${result}`); ``` Perfect! You've integrated Claude with Klavis MCP servers. ## Next Steps Explore available MCP servers REST endpoints and schemas ## Useful Resources * [Anthropic API Documentation](https://docs.anthropic.com/) * [Claude API Reference](https://docs.anthropic.com/en/api/messages) * [MCP Protocol Specification](https://modelcontextprotocol.io/) **Happy building!** šŸš€ # CrewAI Source: https://www.klavis.ai/docs/ai-platform-integration/crewai Build powerful AI agent crews that integrate with Strata MCP servers to build AI agents that can interact with Gmail and Slack. ## Partnership CrewAI has officially showcased their integration with Klavis AI in [this LinkedIn post](https://www.linkedin.com/feed/update/urn:li:activity:7346573584267395072/), demonstrating how to build powerful AI agent crews that can automate complex workflows across multiple platforms. CrewAI and Klavis Integration - Automate your next sales follow-up ## Prerequisites Before we begin, you'll need: Get your API key from OpenAI Platform (CrewAI uses OpenAI as the default model) Get your API key from Klavis AI ## Installation First, install the required packages: ```bash Python theme={null} pip install crewai 'crewai-tools[mcp]' klavis openai ``` ```bash TypeScript theme={null} npm install crewai crewai-tools klavis openai ``` ## Setup Environment Variables ```python Python theme={null} import os # Set environment variables os.environ["OPENAI_API_KEY"] = "your-openai-api-key-here" # Replace with your actual OpenAI API key os.environ["KLAVIS_API_KEY"] = "your-klavis-api-key-here" # Replace with your actual Klavis API key ``` ```typescript TypeScript theme={null} // Set environment variables in your .env file process.env.OPENAI_API_KEY = "your-openai-api-key-here"; // Replace with your actual OpenAI API key process.env.KLAVIS_API_KEY = "your-klavis-api-key-here"; // Replace with your actual Klavis API key ``` ## CrewAI with MCP Integration CrewAI allows you to create specialized AI agent crews where each agent can have access to different MCP tools. This enables sophisticated multi-agent workflows that can: 1. **Create MCP Instances**: Set up connections to external services 2. **Specialized Agents**: Each agent focuses on specific tasks with relevant tools 3. **Collaborative Workflows**: Agents work together in sequential or parallel processes 4. **Tool Discovery**: Automatically discover available tools from MCP servers 5. **Smart Coordination**: CrewAI manages task dependencies and agent collaboration ## Crew AI + Klavis Strata Create a crew agent that helps in assisting user queries using Strata Server ### Step 1 - Create Strata MCP Server with Gmail and Slack ```python Python theme={null} 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}") ``` ```typescript TypeScript theme={null} 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 services if (response.oauthUrls) { for (const [serverName, oauthUrl] of Object.entries(response.oauthUrls)) { window.open(oauthUrl); // Wait for user to complete OAuth await new Promise(resolve => { const input = prompt(`Press OK after completing ${serverName} OAuth authorization...`); resolve(input); }); } } ``` **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 method to use MCP Server with Crew AI This method handles multiple rounds of tool calls until a final response is ready, allowing the AI to chain tool executions for complex tasks. ```python Python theme={null} import json from crewai import Agent, Task, Crew, Process from crewai_tools import MCPServerAdapter def crew_with_mcp_server(mcp_server_url: str, user_query: str): klavis_server_params = [ { "url": mcp_server_url, "transport": "streamable-http" } ] with MCPServerAdapter(klavis_server_params) as all_mcp_tools: print(f"Available tools: {[tool.name for tool in all_mcp_tools]}") klavis_agent = Agent( role="Klavis Query Assistant", goal="Assist the user with their query using available tools", backstory="Expert at assisting users with their queries using available tools", tools=all_mcp_tools, verbose=False, llm="gpt-4o" ) klavis_task = Task( description=f"Answer the user's query: {user_query}", expected_output="Provide a detailed response to the user's query", agent=klavis_agent ) crew = Crew( agents = [klavis_agent], tasks = [klavis_task], process=Process.sequential, verbose=True ) result = crew.kickoff() return result ``` ```typescript TypeScript theme={null} import { Agent, Task, Crew, Process } from 'crewai'; import { MCPServerAdapter } from 'crewai-tools'; async function crewWithMcpServer(mcpServerUrl: string, userQuery: string) { const klavisServerParams = [ { url: mcpServerUrl, transport: "streamable-http" } ]; const mcpAdapter = new MCPServerAdapter(klavisServerParams); const allMcpTools = await mcpAdapter.getTools(); console.log(`Available tools: ${allMcpTools.map(tool => tool.name)}`); const klavisAgent = new Agent({ role: "Klavis Query Assistant", goal: "Assist the user with their query using available tools", backstory: "Expert at assisting users with their queries using available tools", tools: allMcpTools, verbose: false, llm: "gpt-4o" }); const klavisTask = new Task({ description: `Answer the user's query: ${userQuery}`, expectedOutput: "Provide a detailed response to the user's query", agent: klavisAgent }); const crew = new Crew({ agents: [klavisAgent], tasks: [klavisTask], process: Process.Sequential, verbose: true }); const result = await crew.kickoff(); return result; } ``` ### Step 3 - Run! ```python Python theme={null} result = crew_with_mcp_server( mcp_server_url=response.strata_server_url, user_query="Check my latest 5 emails and summarize them in a Slack message to #general" ) print(f"\nFinal Response: {result}") ``` ```typescript TypeScript theme={null} result = await crewWithMcpServer( response.strataServerUrl, "Check my latest emails and summarize them in a Slack message to #updates" ); console.log(`\nFinal Response: ${result}`); ``` Perfect! You've integrated Crew with Strata MCP servers. ## Security Best Practices When using CrewAI with Klavis MCP servers, follow these security guidelines: ```python Python theme={null} def create_secure_crew(): """Demonstrates secure MCP server integration with CrewAI""" # 1. Use environment variables for sensitive data api_key = os.getenv("KLAVIS_API_KEY") if not api_key: raise ValueError("KLAVIS_API_KEY environment variable is required") # 2. Validate server URLs (use HTTPS in production) server_params = [{ "url": server_instance.server_url, "transport": "streamable-http" }] # 3. Always use context managers for proper resource cleanup try: with MCPServerAdapter(server_params) as mcp_tools: # 4. Validate available tools before use if not mcp_tools: raise ValueError("No tools available from MCP server") print(f"āœ… Securely connected with {len(mcp_tools)} tools") # 5. Create agents with limited scope agent = Agent( role="Data Analyst", goal="Analyze data within defined parameters", backstory="You operate within strict security guidelines.", tools=mcp_tools, reasoning=False, # Disable for production verbose=False # Disable verbose logging in production ) return agent except Exception as e: print(f"šŸ”’ Security check failed: {e}") return None # Example usage secure_agent = create_secure_crew() if secure_agent: print("āœ… Secure crew created successfully") ``` ```typescript TypeScript theme={null} function createSecureCrew() { // 1. Use environment variables for sensitive data const apiKey = process.env.KLAVIS_API_KEY; if (!apiKey) { throw new Error("KLAVIS_API_KEY environment variable is required"); } // 2. Validate server URLs (use HTTPS in production) const serverParams = [{ url: serverInstance.serverUrl, transport: "streamable-http" }]; // 3. Always handle errors properly try { // 4. Validate available tools before use const mcpTools = new MCPServerAdapter(serverParams); if (!mcpTools) { throw new Error("No tools available from MCP server"); } console.log(`āœ… Securely connected with tools`); // 5. Create agents with limited scope const agent = new Agent({ role: "Data Analyst", goal: "Analyze data within defined parameters", backstory: "You operate within strict security guidelines.", tools: mcpTools, reasoning: false, // Disable for production verbose: false // Disable verbose logging in production }); return agent; } catch (error) { console.error(`šŸ”’ Security check failed: ${error}`); return null; } } // Example usage const secureAgent = createSecureCrew(); if (secureAgent) { console.log("āœ… Secure crew created successfully"); } ``` ## Available MCP Servers CrewAI works with all Klavis MCP servers. Here are some popular options: Gmail, Slack, Discord, Outlook YouTube, Notion, Google Docs, WordPress GitHub, Jira, Linear, Confluence Google Sheets, Supabase, PostgreSQL Salesforce, HubSpot, Asana, ClickUp Google Drive, Dropbox, OneDrive ## Summary CrewAI + Klavis integration enables you to build sophisticated multi-agent AI systems with real-world capabilities. Key benefits include: ### šŸš€ **CrewAI + Klavis Benefits:** * **Seamless Integration**: MCPServerAdapter makes MCP connection effortless * **Agent Specialization**: Each agent can focus on specific domains * **Scalable Architecture**: Easy to add more agents and MCP servers * **Professional AI Teams**: Create sophisticated multi-agent systems * **Real-World Impact**: Connect AI to actual business tools and services **Ready to build your first AI crew?** Start with a simple agent and expand from there! šŸš€šŸ‘„ # Fireworks AI Source: https://www.klavis.ai/docs/ai-platform-integration/fireworks-ai Learn how to build AI agents that integrate Fireworks AI's LLMs with Klavis MCP Servers ## Prerequisites Before we begin, you'll need: Get your API key from Fireworks AI Get your API key from Klavis AI ## Installation First, install the required packages: ```bash Python theme={null} pip install fireworks-ai klavis ``` ```bash TypeScript theme={null} npm install fireworks-ai klavis ``` ## Setup Environment Variables ```python Python theme={null} import os # Set environment variables os.environ["FIREWORKS_API_KEY"] = "your-fireworks-api-key-here" # Replace with your actual Fireworks API key os.environ["KLAVIS_API_KEY"] = "your-klavis-api-key-here" # Replace with your actual Klavis API key ``` ```typescript TypeScript theme={null} // Set environment variables in your .env file process.env.FIREWORKS_API_KEY = "your-fireworks-api-key-here"; // Replace with your actual Fireworks API key process.env.KLAVIS_API_KEY = "your-klavis-api-key-here"; // Replace with your actual Klavis API key ``` ## Basic Setup ```python Python theme={null} import os import json from fireworks.client import Fireworks from klavis import Klavis from klavis.types import McpServerName, ToolFormat # Initialize clients fireworks_client = Fireworks(api_key=os.getenv("FIREWORKS_API_KEY")) klavis_client = Klavis(api_key=os.getenv("KLAVIS_API_KEY")) ``` ```typescript TypeScript theme={null} import Fireworks from 'fireworks-ai'; import { KlavisClient, Klavis } from 'klavis'; // Initialize clients const fireworksClient = new Fireworks({ apiKey: process.env.FIREWORKS_API_KEY }); const klavisClient = new KlavisClient({ apiKey: process.env.KLAVIS_API_KEY }); ``` ## AI Agent with MCP Integration Now we'll create an intelligent agent that can use MCP servers through Klavis API. This agent will: 1. **Discover Tools**: Automatically find available tools from MCP servers 2. **Function Calling**: Use Fireworks AI's function calling capabilities 3. **Tool Execution**: Execute tools through Klavis API 4. **Smart Responses**: Generate intelligent responses based on tool results ```python Python theme={null} class Agent: def __init__(self, fireworks_client, klavis_client, mcp_server_url): self.fireworks = fireworks_client self.klavis = klavis_client self.mcp_server_url = mcp_server_url self.model = "accounts/fireworks/models/qwen2p5-72b-instruct" print(f"šŸ¤– Agent initialized with model: {self.model}") def process_request(self, user_message): # 1. Get available tools mcp_tools = self.klavis.mcp_server.list_tools( server_url=self.mcp_server_url, format=ToolFormat.OPENAI ) # 2. Call LLM with tools messages = [ {"role": "system", "content": "You are a helpful assistant."}, {"role": "user", "content": user_message} ] response = self.fireworks.chat.completions.create( model=self.model, messages=messages, tools=mcp_tools.tools ) assistant_message = response.choices[0].message messages.append(assistant_message) # 3. If LLM wants to use tools if assistant_message.tool_calls: # Execute each tool call for tool_call in assistant_message.tool_calls: tool_name = tool_call.function.name tool_args = json.loads(tool_call.function.arguments) print(f"šŸ› ļø Calling tool: {tool_name} with args: {tool_args}") # Call tool via Klavis SDK tool_result = self.klavis.mcp_server.call_tools( server_url=self.mcp_server_url, tool_name=tool_name, tool_args=tool_args ) messages.append({ "role": "tool", "tool_call_id": tool_call.id, "content": str(tool_result) }) # 4. Get final response from LLM final_response = self.fireworks.chat.completions.create( model=self.model, messages=messages ) return final_response.choices[0].message.content # If no tools needed, return the assistant message directly return assistant_message.content ``` ```typescript TypeScript theme={null} class Agent { private fireworks: Fireworks; private klavis: KlavisClient; private mcpServerUrl: string; private model: string; constructor(fireworksClient: Fireworks, klavisClient: KlavisClient, mcpServerUrl: string) { this.fireworks = fireworksClient; this.klavis = klavisClient; this.mcpServerUrl = mcpServerUrl; this.model = "accounts/fireworks/models/qwen2p5-72b-instruct"; console.log(`šŸ¤– Agent initialized with model: ${this.model}`); } async processRequest(userMessage: string) { // 1. Get available tools const mcpTools = await this.klavis.mcpServer.listTools({ serverUrl: this.mcpServerUrl, format: Klavis.ToolFormat.Openai }); // 2. Call LLM with tools const messages = [ { role: "system", content: "You are a helpful assistant." }, { role: "user", content: userMessage } ]; const response = await this.fireworks.chat.completions.create({ model: this.model, messages: messages, tools: mcpTools.tools }); const assistantMessage = response.choices[0].message; messages.push(assistantMessage); // 3. If LLM wants to use tools if (assistantMessage.tool_calls) { // Execute each tool call for (const toolCall of assistantMessage.tool_calls) { const toolName = toolCall.function.name; const toolArgs = JSON.parse(toolCall.function.arguments); console.log(`šŸ› ļø Calling tool: ${toolName} with args:`, toolArgs); // Call tool via Klavis SDK const toolResult = await this.klavis.mcpServer.callTools({ serverUrl: this.mcpServerUrl, toolName: toolName, toolArgs: toolArgs }); messages.push({ role: "tool", tool_call_id: toolCall.id, content: JSON.stringify(toolResult) }); } // 4. Get final response from LLM const finalResponse = await this.fireworks.chat.completions.create({ model: this.model, messages: messages }); return finalResponse.choices[0].message.content; } // If no tools needed, return the assistant message directly return assistantMessage.content; } } ``` ## Use Case Examples ### Example 1: Summarize YouTube Video Set up Fireworks AI and Klavis API clients Create a YouTube MCP server instance Use the agent to analyze and summarize a YouTube video ```python Python theme={null} YOUTUBE_VIDEO_URL = "https://www.youtube.com/watch?v=kPXvf2-C_Hs" # Pick a video you like! # 1. Create YouTube MCP server instance youtube_mcp_instance = klavis_client.mcp_server.create_server_instance( server_name=McpServerName.YOUTUBE, user_id="1234" ) # 2. Create an agent with YouTube MCP server agent = Agent(fireworks_client, klavis_client, youtube_mcp_instance.server_url) # 3. Process the request response = agent.process_request( f"Summarize this YouTube video with timestamps: {YOUTUBE_VIDEO_URL}" ) print(response) ``` ```typescript TypeScript theme={null} const YOUTUBE_VIDEO_URL = "https://www.youtube.com/watch?v=kPXvf2-C_Hs"; // Pick a video you like! // 1. Create YouTube MCP server instance const youtubeMcpInstance = await klavisClient.mcpServer.createServerInstance({ serverName: Klavis.McpServerName.Youtube, userId: "1234" }); // 2. Create an agent with YouTube MCP server const agent = new Agent(fireworksClient, klavisClient, youtubeMcpInstance.serverUrl); // 3. Process the request const response = await agent.processRequest( `Summarize this YouTube video with timestamps: ${YOUTUBE_VIDEO_URL}` ); console.log(response); ``` ### Example 2: Send Email via Gmail Gmail integration requires OAuth authentication, so you'll need to authorize the application in your browser. Create a Gmail MCP server instance Complete OAuth flow for Gmail access Use the agent to send an email ```python Python theme={null} import webbrowser # Create Gmail MCP server instance gmail_mcp_instance = klavis_client.mcp_server.create_server_instance( server_name=McpServerName.GMAIL, user_id="1234" ) # Redirect to Gmail OAuth page webbrowser.open(gmail_mcp_instance.oauth_url) print(f"šŸ” Opening OAuth authorization for Gmail, if you are not redirected, please open the following URL in your browser: {gmail_mcp_instance.oauth_url}") EMAIL_SUBJECT = "Hello, World!" EMAIL_BODY = "This is a test email sent using Fireworks AI and Klavis integration." EMAIL_RECIPIENT = "recipient@example.com" # Replace with your email # After OAuth authorization, create an agent with Gmail MCP server agent = Agent(fireworks_client, klavis_client, gmail_mcp_instance.server_url) # Send the email response = agent.process_request( f"Send an email to {EMAIL_RECIPIENT} with subject {EMAIL_SUBJECT} and body {EMAIL_BODY}" ) print(response) ``` ```typescript TypeScript theme={null} // Create Gmail MCP server instance const gmailMcpInstance = await klavisClient.mcpServer.createServerInstance({ serverName: Klavis.McpServerName.Gmail, userId: "1234" }); // Redirect to Gmail OAuth page console.log("šŸ” Opening OAuth authorization for Gmail"); console.log(`If you are not redirected, please open the following URL in your browser: ${gmailMcpInstance.oauthUrl}`); // In a web environment, you might redirect the user window.open(gmailMcpInstance.oauthUrl); const EMAIL_SUBJECT = "Hello, World!"; const EMAIL_BODY = "This is a test email sent using Fireworks AI and Klavis integration."; const EMAIL_RECIPIENT = "recipient@example.com"; // Replace with your email // After OAuth authorization, create an agent with Gmail MCP server const agent = new Agent(fireworksClient, klavisClient, gmailMcpInstance.serverUrl); // Send the email const response = await agent.processRequest( `Send an email to ${EMAIL_RECIPIENT} with subject ${EMAIL_SUBJECT} and body ${EMAIL_BODY}` ); console.log(response); ``` ## Next Steps Try other available servers like Slack, Notion, CRM, etc. Experiment with various models like Llama, Mixtral, or Deepseek for different use cases Create sophisticated agents that combine Gmail + Slack + Notion for complete business automation Scale these patterns for production applications ## Useful Resources * [Fireworks AI Documentation](https://docs.fireworks.ai/) * [Klavis AI Documentation](https://www.klavis.ai/docs/) * [MCP Protocol Specification](https://modelcontextprotocol.io/) * [Klavis MCP Servers](/mcp-server) **Happy building with Fireworks AI and Klavis!** šŸš€ # Gemini Source: https://www.klavis.ai/docs/ai-platform-integration/gemini Learn how to build AI agents that integrate Google's Gemini with Strata MCP servers to build AI agents that can interact with Gmail and Slack. [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/klavis-ai/klavis/blob/main/examples/google-genai/Use_Klavis_with_Gemini.ipynb) # Gemini + Klavis AI Integration This tutorial demonstrates how to use Google's Gemini with function calling with Klavis MCP (Model Context Protocol) servers. ## Prerequisites Before we begin, you'll need: Get your API key from Google AI Studio Get your API key from Klavis AI ## Installation First, install the required packages: ```bash Python theme={null} pip install google-genai klavis ``` ```bash TypeScript theme={null} npm install @google/genai klavis ``` ## Full Code Examples For complete working examples, check out the source code: ## Setup Environment Variables ```python Python theme={null} import os # Set environment variables os.environ["GEMINI_API_KEY"] = "YOUR_GEMINI_API_KEY" # Replace with your actual Gemini API key os.environ["KLAVIS_API_KEY"] = "YOUR_KLAVIS_API_KEY" # Replace with your actual Klavis API key ``` ```typescript TypeScript theme={null} import { GoogleGenAI } from '@google/genai'; import { KlavisClient, Klavis } from 'klavis'; // Set environment variables process.env.GEMINI_API_KEY = "YOUR_GEMINI_API_KEY"; // Replace with your actual Gemini API key process.env.KLAVIS_API_KEY = "YOUR_KLAVIS_API_KEY"; // Replace with your actual Klavis API key ``` ### Step 1 - Create Strata MCP Server with Gmail and Slack ```python Python theme={null} 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}") ``` ```typescript TypeScript theme={null} 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 services if (response.oauthUrls) { for (const [serverName, oauthUrl] of Object.entries(response.oauthUrls)) { window.open(oauthUrl); // Wait for user to complete OAuth await new Promise(resolve => { const input = prompt(`Press OK after completing ${serverName} OAuth authorization...`); resolve(input); }); } } ``` **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 method to use MCP Server with Claude This method handles multiple rounds of tool calls until a final response is ready, allowing the AI to chain tool executions for complex tasks. ```python Python theme={null} import json from google import genai from google.genai import types def gemini_with_mcp_server(mcp_server_url: str, user_query: str): gemini_client = genai.Client(api_key=os.getenv("GEMINI_API_KEY")) contents = [] contents.append(types.Content(role="user", parts=[types.Part(text=user_query)])) mcp_server_tools = klavis_client.mcp_server.list_tools( server_url=mcp_server_url, format=ToolFormat.GEMINI ) max_iterations = 10 iteration = 0 while iteration < max_iterations: iteration += 1 response = gemini_client.models.generate_content( model='gemini-2.5-flash', contents=contents, config=types.GenerateContentConfig(tools=mcp_server_tools.tools) ) if response.candidates and response.candidates[0].content.parts: contents.append(response.candidates[0].content) # Check if there are function calls to execute has_function_calls = False for part in response.candidates[0].content.parts: if hasattr(part, 'function_call') and part.function_call: has_function_calls = True function_name = part.function_call.name function_args = dict(part.function_call.args) print(f"Calling: {function_name}, with args: {function_args}") result = klavis_client.mcp_server.call_tools( server_url=mcp_server_url, tool_name=function_name, tool_args=function_args ) function_response_part = types.Part.from_function_response( name=function_name, response={'result': result.result} ) function_response_content = types.Content( role='tool', parts=[function_response_part] ) contents.append(function_response_content) if has_function_calls: continue else: return response.text else: return "No response generated." return "Max iterations reached without final response" ``` ```typescript TypeScript theme={null} async function geminiWithMcpServer(mcpServerUrl: string, userQuery: string) { const geminiClient = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY }); const contents = []; contents.push({ role: "user", parts: [{ text: userQuery }] }); const mcpServerTools = await klavisClient.mcpServer.listTools({ serverUrl: mcpServerUrl, format: Klavis.ToolFormat.Gemini }); const maxIterations = 10; let iteration = 0; while (iteration < maxIterations) { iteration++; const response = await geminiClient.models.generateContent({ model: 'gemini-2.5-flash', contents: contents, config: { tools: mcpServerTools.tools } }); if (response.candidates && response.candidates[0].content.parts) { contents.push(response.candidates[0].content); // Check if there are function calls to execute let hasFunctionCalls = false; for (const part of response.candidates[0].content.parts) { if (part.functionCall) { hasFunctionCalls = true; const functionName = part.functionCall.name; const functionArgs = part.functionCall.args; console.log(`šŸ”§ Calling: ${functionName}, with args:`, functionArgs); const result = await klavisClient.mcpServer.callTools({ serverUrl: mcpServerUrl, toolName: functionName, toolArgs: functionArgs }); const functionResponsePart = { functionResponse: { name: functionName, response: { result: result.result } } }; const functionResponseContent = { role: 'tool', parts: [functionResponsePart] }; contents.push(functionResponseContent); } } if (hasFunctionCalls) { continue; } else { return response.text; } } else { return "No response generated."; } } return "Max iterations reached without final response"; } ``` ### Step 3 - Run! ```python Python theme={null} result = gemini_with_mcp_server( mcp_server_url=response.strata_server_url, user_query="Check my latest 5 gmails and summarize them in a Slack message to #engineering" ) print(f"\nšŸ¤– Final Response: {result}") ``` ```typescript TypeScript theme={null} const result = await geminiWithMcpServer( response.strataServerUrl, "Check my latest 5 gmails and summarize them in a Slack message to #engineering" ); console.log(`\nšŸ¤– Final Response: ${result}`); ``` Perfect! You've integrated Gemini with Klavis MCP servers. ## Next Steps Try other available servers like Slack, Notion, GitHub, etc. Build workflows that combine text, images, and other media Scale these patterns for production applications Build custom MCP servers for your specific needs ## Useful Resources * [Google AI Documentation](https://ai.google.dev/) * [Gemini API Reference](https://ai.google.dev/api) * [Klavis AI Documentation](https://www.klavis.ai/docs/) * [MCP Protocol Specification](https://modelcontextprotocol.io/) * [Klavis MCP Servers](/mcp-server) **Happy building!** šŸš€ # Google ADK Source: https://www.klavis.ai/docs/ai-platform-integration/google-adk This tutorial demonstrates how to integrate Google Agent Development Kit (ADK) with Klavis MCP servers to build AI agents that can interact with Gmail and Slack. Google ADK and Klavis Integration - Build AI agents with MCP tools You can find the complete example code in Klavis GitHub repository **[here ->](https://github.com/Klavis-AI/klavis/tree/main/examples/google_adk/python)** ## Prerequisites Before we begin, you'll need: [Google API key](https://console.cloud.google.com/apis/credentials) and [Klavis API key](https://www.klavis.ai/home/api-keys). ## Installation First, install the required packages: ```bash theme={null} pip install google-adk klavis ``` ## Setup Environment Variables ```python theme={null} import os from dotenv import load_dotenv load_dotenv() os.environ["KLAVIS_API_KEY"] = "YOUR_KLAVIS_API_KEY" # Replace ``` ### Step 1 - Create an Agent Project Run the ADK create command to start a new agent project: ```bash theme={null} adk create my_agent ``` This will create the following project structure: ``` my_agent/ agent.py # main agent code .env # API keys or project IDs __init__.py ``` ### Step 2 - Configure Agent with Klavis MCP The `agent.py` file contains a `root_agent` definition which is the only required element of an ADK agent. Update your `agent.py` to integrate Klavis MCP servers: ```python theme={null} import os import webbrowser from google.adk.agents.llm_agent import Agent from google.adk.tools.mcp_tool import StreamableHTTPConnectionParams from google.adk.tools.mcp_tool.mcp_toolset import McpToolset from klavis import Klavis from klavis.types import McpServerName from dotenv import load_dotenv load_dotenv() KLAVIS_API_KEY = os.getenv("KLAVIS_API_KEY") # Initialize Klavis and set up Strata server klavis_client = Klavis(api_key=KLAVIS_API_KEY) user_id = "user_123" # Create Strata server with multiple MCP servers strata_response = klavis_client.mcp_server.create_strata_server( servers=[McpServerName.GMAIL, McpServerName.SLACK], user_id=user_id ) # Handle OAuth authentication if strata_response.oauth_urls: for server_name, oauth_url in strata_response.oauth_urls.items(): user_integration_auth = klavis_client.user.get_user_auth( user_id=user_id, server_name=server_name ) if not user_integration_auth.is_authenticated: print(f"šŸ” Opening OAuth for {server_name}...") webbrowser.open(oauth_url) input(f"Press Enter after completing {server_name} OAuth authorization...") mcp_server_url = strata_response.strata_server_url # Create AI agent with MCP toolset (exposed at module level for ADK) root_agent = Agent( name="my_agent", model="gemini-2.5-flash", description="An agent with access to tools through Klavis MCP", instruction="You are a helpful assistant with access to MCP tools.", tools=[ McpToolset( connection_params=StreamableHTTPConnectionParams( url=mcp_server_url, ), ) ], ) ``` **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 3 - Run Your Agent Launch the web interface to interact with your agent: ```bash theme={null} adk web ``` This will start a local web server where you can chat with your agent and watch it use the Gmail and Slack MCP tools. Perfect! You've integrated Google ADK with Klavis MCP servers. ## Next Steps Explore available MCP servers REST endpoints and schemas ## Useful Resources * [Google ADK Documentation](https://google.github.io/adk/) * [Google ADK GitHub](https://github.com/google/adk) * [MCP Protocol Specification](https://modelcontextprotocol.io/) **Happy building!** šŸš€ # LangChain Source: https://www.klavis.ai/docs/ai-platform-integration/langchain This tutorial demonstrates how to integrate LangChain's agent framework with Strata MCP servers to build AI agents that can interact with Gmail and Slack. ## Prerequisites Before we begin, you'll need [OpenAI API key](\(https://platform.openai.com/api-keys\)) and [Klavis API key](https://www.klavis.ai/home/api-keys). ## Installation First, install the required packages: ```bash Python theme={null} pip install langchain-mcp-adapters langgraph langchain-openai klavis ``` ```bash TypeScript theme={null} npm install @langchain/mcp-adapters @langchain/langgraph @langchain/openai klavis ``` ## Setup Environment Variables ```python Python theme={null} import os os.environ["OPENAI_API_KEY"] = "YOUR_OPENAI_API_KEY" # Replace os.environ["KLAVIS_API_KEY"] = "YOUR_KLAVIS_API_KEY" # Replace ``` ```typescript TypeScript theme={null} // Set environment variables process.env.OPENAI_API_KEY = "YOUR_OPENAI_API_KEY"; // Replace with your actual OpenAI API key process.env.KLAVIS_API_KEY = "YOUR_KLAVIS_API_KEY"; // Replace with your actual Klavis API key ``` ### Step 1 - Create Strata MCP Server with Gmail and Slack ```python Python theme={null} 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}") ``` ```typescript TypeScript theme={null} 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 services if (response.oauthUrls) { for (const [serverName, oauthUrl] of Object.entries(response.oauthUrls)) { window.open(oauthUrl); // Wait for user to complete OAuth await new Promise(resolve => { const input = prompt(`Press OK after completing ${serverName} OAuth authorization...`); resolve(input); }); } } ``` *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 ```python Python theme={null} 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!") ``` ```typescript TypeScript theme={null} // 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: "streamable_http" } } }); // Get tools from Strata MCP server const tools = await mcpClient.getTools(); // Create agent with MCP-based tools const agent = createReactAgent({ llm: llm, tools: tools, systemMessage: "You are a helpful assistant that uses MCP tools to interact with Gmail and Slack." }); console.log("šŸ¤– LangChain agent created successfully!"); ``` ### Step 3 - Run! ```python Python theme={null} 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}") ``` ```typescript TypeScript theme={null} try { const response = await agent.invoke({ messages: [{ role: "user", content: "Check my latest emails and summarize them in a Slack message to #updates" }] }); console.log(`\nšŸ¤– Final Response:`, response); } catch (error) { console.error("Error during agent execution:", error); } finally { await mcpClient.close(); } ``` Perfect! You've integrated LangChain with Klavis MCP servers. ## Next Steps Explore available MCP servers REST endpoints and schemas ## Useful Resources * [LangChain Documentation](https://python.langchain.com/docs/) * [LangGraph Documentation](https://langchain-ai.github.io/langgraph/) * [LangChain MCP Adapters](https://pypi.org/project/langchain-mcp-adapters/) * [MCP Protocol Specification](https://modelcontextprotocol.io/) *Happy building* šŸš€ # LlamaIndex Source: https://www.klavis.ai/docs/ai-platform-integration/llamaindex Learn how to build AI agents that integrate with Strata MCP servers to build AI agents that can interact with Gmail and Slack. ## Partnership LlamaIndex has officially showcased their integration with Klavis AI in [this LinkedIn post](https://www.linkedin.com/posts/llamaindex_build-ai-agents-that-connect-to-youtube-activity-7344107221221355521-UrOl?utm_source=share\&utm_medium=member_desktop\&rcm=ACoAACh0ewEBh9MR1nb_U_x3e5bqgDYgETJ8d5Y), demonstrating how to build AI agents that connect to MCP Servers in just a few lines of code. LlamaIndex and Klavis Integration - Build AI agents that connect to MCP Servers ## Prerequisites Before we begin, you'll need: Get your API key from OpenAI Platform (LlamaIndex uses OpenAI as the default LLM) Get your API key from Klavis AI ## Installation First, install the required packages: ```bash Python theme={null} pip install llama-index llama-index-tools-mcp klavis ``` ```bash TypeScript theme={null} npm install @llamaindex/tools @llamaindex/workflow @llamaindex/openai klavis ``` ## Setup Environment Variables ```python Python theme={null} import os # Set environment variables os.environ["OPENAI_API_KEY"] = "your-openai-api-key-here" # Replace with your actual OpenAI API key os.environ["KLAVIS_API_KEY"] = "your-klavis-api-key-here" # Replace with your actual Klavis API key ``` ```typescript TypeScript theme={null} // Set environment variables in your .env file process.env.OPENAI_API_KEY = "your-openai-api-key-here"; // Replace with your actual OpenAI API key process.env.KLAVIS_API_KEY = "your-klavis-api-key-here"; // Replace with your actual Klavis API key ``` ## Basic Setup ```python Python theme={null} from klavis import Klavis from klavis.types import McpServerName from llama_index.llms.openai import OpenAI from llama_index.tools.mcp import ( BasicMCPClient, get_tools_from_mcp_url, aget_tools_from_mcp_url ) # Initialize clients klavis_client = Klavis(api_key=os.getenv("KLAVIS_API_KEY")) llm = OpenAI(model="gpt-4o-mini", api_key=os.getenv("OPENAI_API_KEY")) ``` ```typescript TypeScript theme={null} import { KlavisClient, Klavis } from 'klavis'; import { mcp } from "@llamaindex/tools"; import { agent, multiAgent } from "@llamaindex/workflow"; import { openai } from "@llamaindex/openai"; // Initialize clients const klavisClient = new KlavisClient({ apiKey: process.env.KLAVIS_API_KEY }); ``` ### Step 1 - Create Strata MCP Server with Gmail and Slack ```python Python theme={null} 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}") ``` ```typescript TypeScript theme={null} 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 services if (response.oauthUrls) { for (const [serverName, oauthUrl] of Object.entries(response.oauthUrls)) { window.open(oauthUrl); // Wait for user to complete OAuth await new Promise(resolve => { const input = prompt(`Press OK after completing ${serverName} OAuth authorization...`); resolve(input); }); } } ``` **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 method to use MCP Server with LlamaIndex This method handles multiple rounds of tool calls until a final response is ready, allowing the AI to chain tool executions for complex tasks. ```python Python theme={null} import json from llama_index.core.agent.workflow import FunctionAgent, AgentWorkflow async def llamaindex_with_mcp_server(mcp_server_url: str, user_query: str): llm = OpenAI(model="gpt-4o-mini", api_key=os.getenv("OPENAI_API_KEY")) all_tools = await aget_tools_from_mcp_url( mcp_server_url, client=BasicMCPClient(mcp_server_url) ) communication_agent = FunctionAgent( name="communication_agent", description="Agent that can read emails from Gmail and send messages to Slack", tools=all_tools, llm=llm, system_prompt="You are a helpful assistant. Use the available tools to answer the user's question.", max_iterations=10 ) workflow = AgentWorkflow( agents=[communication_agent], root_agent="communication_agent" ) resp = await workflow.run(user_msg=user_query) return resp.response.content ``` ```typescript TypeScript theme={null} async function llamaindexWithMcpServer(mcpServerUrl: string, userQuery: string) { const llm = new openai.OpenAI({ model: "gpt-4o-mini", apiKey: process.env.OPENAI_API_KEY }); const allTools = await mcp.getToolsFromMcpUrl( mcpServerUrl, new mcp.BasicMCPClient(mcpServerUrl) ); const communicationAgent = new agent.FunctionAgent({ name: "communication_agent", description: "Agent that can read emails from Gmail and send messages to Slack", tools: allTools, llm: llm, systemPrompt: "You are a helpful assistant. Use the available tools to answer the user's question.", maxIterations: 10 }); const workflow = new agent.AgentWorkflow({ agents: [communicationAgent], rootAgent: "communication_agent" }); const resp = await workflow.run({ userMsg: userQuery }); return resp.response.content; } ``` ### Step 3 - Run! ```python Python theme={null} result = await llamaindex_with_mcp_server( mcp_server_url=response.strata_server_url, user_query="Check my latest 5 emails and summarize them in a Slack message to #general" ) print(f"\nFinal Response: {result}") ``` ```typescript TypeScript theme={null} result = await llamaindexWithMcpServer( response.strataServerUrl, "Check my latest 5 emails and summarize them in a Slack message to #general" ); console.log(`\nFinal Response: ${result}`); ``` Perfect! You've integrated LLamaIndex with Strata MCP servers. ## Next Steps Explore available MCP servers REST endpoints and schemas ## Useful Resources * [LlamaIndex Documentation](https://docs.llamaindex.ai/) * [Klavis AI Documentation](https://www.klavis.ai/docs/) * [MCP Protocol Specification](https://modelcontextprotocol.io/) * [Klavis MCP Servers](/mcp-server) **Happy building with LlamaIndex and Klavis!** šŸš€ # Mastra Source: https://www.klavis.ai/docs/ai-platform-integration/mastra Learn how to build AI agents that integrate Mastra framework with Klavis MCP Servers for enhanced functionality ## Partnership Mastra has officially featured Klavis AI in [their MCP registry documentation](https://mastra.ai/en/docs/tools-mcp/mcp-overview#connecting-to-an-mcp-registry), showcasing how to connect to MCP servers for building powerful AI agents. Mastra and Klavis Integration - Connect to MCP servers through registry ## Prerequisites Before we begin, you'll need [OpenAI API key](https://platform.openai.com/api-keys) and [Klavis API key](https://www.klavis.ai/home/api-keys). You can find the complete example code in Klavis GitHub repository: **[šŸ“ Checkout here](https://github.com/Klavis-AI/klavis/tree/main/examples/mastra-klavis)** ## Setup Environment Variables Create a `.env` file in your project root: ```env theme={null} OPENAI_API_KEY=your_openai_api_key_here KLAVIS_API_KEY=your_klavis_api_key_here ``` ## Project Structure ``` mastra-klavis-example/ ā”œā”€ā”€ src/ │ └── mastra/ │ └── index.ts ā”œā”€ā”€ package.json └── tsconfig.json ``` ## Code Example ```typescript theme={null} import { Mastra } from '@mastra/core/mastra'; import { Agent } from '@mastra/core/agent'; import { openai } from '@ai-sdk/openai'; import { MCPClient } from '@mastra/mcp'; import { KlavisClient, Klavis } from 'klavis'; import open from 'open'; // Creates an MCP Agent with tools from Klavis Strata server export const createMcpAgent = async (userId: string = 'test-user'): Promise => { const klavis = new KlavisClient({ apiKey: process.env.KLAVIS_API_KEY! }); // Create a Strata MCP Server with Gmail and Slack const response = await klavis.mcpServer.createStrataServer({ servers: [Klavis.McpServerName.Gmail, Klavis.McpServerName.Slack], userId }); // Handle OAuth authorization for each service if (response.oauthUrls) { for (const [serverName, oauthUrl] of Object.entries(response.oauthUrls)) { await open(oauthUrl); console.log(`Please complete ${serverName} OAuth authorization at: ${oauthUrl}`); } } // Initialize the MCP client with Strata server URL const mcpClient = new MCPClient({ servers: { strata: { url: new URL(response.strataServerUrl) } } }); // Create agent return new Agent({ name: 'MCP Agent', instructions: `You are an AI agent with access to MCP tools.`, model: openai('gpt-4o-mini'), tools: await mcpClient.getTools() }); }; const agent = await createMcpAgent(); export const mastra = new Mastra({ agents: { agent } }); ``` ## Running the Agent ```bash theme={null} npm install npm run dev ``` ## Video Tutorial