# Authorize Airtable Source: https://docs.klavis.ai/api-reference/airtable-oauth/authorize-airtable get /oauth/airtable/authorize Start Airtable OAuth flow Parameters: - instance_id: Identifier for the instance requesting authorization - client_id: Optional client ID for white labeling - scope: Optional scopes to request (space-separated) - redirect_url: Optional URL to redirect to after authorization completes # Authorize Asana Source: https://docs.klavis.ai/api-reference/asana-oauth/authorize-asana get /oauth/asana/authorize Start Asana OAuth flow Parameters: - instance_id: Identifier for the instance requesting authorization - client_id: Optional client ID for white labeling - scope: Optional scopes to request (comma-separated) - redirect_url: Optional URL to redirect to after authorization completes # Authorize Attio Source: https://docs.klavis.ai/api-reference/attio-oauth/authorize-attio get /oauth/attio/authorize Start Attio OAuth flow Parameters: - instance_id: Identifier for the instance requesting authorization - client_id: Optional client ID for white labeling - redirect_url: Optional URL to redirect to after authorization completes # Authorize Close Source: https://docs.klavis.ai/api-reference/close-oauth/authorize-close get /oauth/close/authorize Start Close OAuth flow Parameters: - instance_id: Identifier for the instance requesting authorization - client_id: Optional client ID for white labeling - scope: Optional scopes to request (comma-separated) - redirect_url: Optional URL to redirect to after authorization completes # Authorize Confluence Source: https://docs.klavis.ai/api-reference/confluence-oauth/authorize-confluence get /oauth/confluence/authorize Start Confluence OAuth flow Parameters: - instance_id: Identifier for the instance requesting authorization - client_id: Optional client ID for white labeling - scope: Optional scopes to request (comma-separated) - redirect_url: Optional URL to redirect to after authorization completes # Authorize Github Source: https://docs.klavis.ai/api-reference/github-oauth/authorize-github get /oauth/github/authorize Start GitHub OAuth flow Parameters: - instance_id: Identifier for the instance requesting authorization - client_id: Optional client ID for white labeling - scope: Optional scopes to request (comma-separated) - redirect_url: Optional URL to redirect to after authorization completes # Authorize Gmail Source: https://docs.klavis.ai/api-reference/gmail-oauth/authorize-gmail get /oauth/gmail/authorize Start Gmail OAuth flow Parameters: - instance_id: Identifier for the instance requesting authorization - client_id: Optional client ID for white labeling - scope: Optional scopes to request (comma-separated) - redirect_url: Optional URL to redirect to after authorization completes # Authorize Gcalendar Source: https://docs.klavis.ai/api-reference/google-calendar-oauth/authorize-google-calendar get /oauth/gcalendar/authorize Start Google Calendar OAuth flow Parameters: - instance_id: Identifier for the instance requesting authorization - client_id: Optional client ID for white labeling - scope: Optional scopes to request (comma-separated) - redirect_url: Optional URL to redirect to after authorization completes # Authorize Gdocs Source: https://docs.klavis.ai/api-reference/google-docs-oauth/authorize-google-docs get /oauth/gdocs/authorize Start Google Docs OAuth flow Parameters: - instance_id: Identifier for the instance requesting authorization - client_id: Optional client ID for white labeling - scope: Optional scopes to request (comma-separated) - redirect_url: Optional URL to redirect to after authorization completes # Authorize Gdrive Source: https://docs.klavis.ai/api-reference/google-drive-oauth/authorize-google-drive get /oauth/gdrive/authorize Start Google Drive OAuth flow Parameters: - instance_id: Identifier for the instance requesting authorization - client_id: Optional client ID for white labeling - scope: Optional scopes to request (comma-separated) - redirect_url: Optional URL to redirect to after authorization completes # Authorize Gsheets Source: https://docs.klavis.ai/api-reference/google-sheets-oauth/authorize-google-sheets get /oauth/gsheets/authorize Start Google Sheets OAuth flow Parameters: - instance_id: Identifier for the instance requesting authorization - client_id: Optional client ID for white labeling - scope: Optional scopes to request (comma-separated) - redirect_url: Optional URL to redirect to after authorization completes # Introduction Source: https://docs.klavis.ai/api-reference/introduction Klavis provides API for developers to integrate MCP to your AI application. ## Base URL The Klavis API is built on REST principles. We enforce HTTPS in every request to improve data security, integrity, and privacy. The API does not support HTTP. All requests contain the following base URL: ```bash https://api.klavis.ai ``` ## Authentication To authenticate you need to add an Authorization header with the contents of the header being Bearer key\_123456789 where key\_123456789 is your API Key. ```bash Authorization: Bearer key_123456789 ``` ## Response codes Klavis uses standard HTTP codes to indicate the success or failure of your requests. In general, 2xx HTTP codes correspond to success, 4xx codes are for user-related failures, and 5xx codes are for infrastructure issues. | Status | Description | | ------ | --------------------------------------- | | 200 | Successful request. | | 400 | Check that the parameters were correct. | | 401 | The API key used was missing. | | 403 | The API key used was invalid. | | 404 | The resource was not found. | | 429 | The rate limit was exceeded. | | 5xx | Indicates an error with Klavis servers. | Check Error Codes for a comprehensive breakdown of all possible API errors. ## Rate limit The default maximum rate limit is 2 requests per second. This number can be increased for trusted senders by request. After that, you'll hit the rate limit and receive a 429 response error code. # Authorize Jira Source: https://docs.klavis.ai/api-reference/jira-oauth/authorize-jira get /oauth/jira/authorize Start Jira OAuth flow Parameters: - instance_id: Identifier for the instance requesting authorization - client_id: Optional client ID for white labeling - scope: Optional scopes to request (comma-separated) - redirect_url: Optional URL to redirect to after authorization completes # Authorize Linear Source: https://docs.klavis.ai/api-reference/linear-oauth/authorize-linear get /oauth/linear/authorize Start Linear OAuth flow Parameters: - instance_id: Identifier for the instance requesting authorization - client_id: Optional client ID for white labeling - scope: Optional scopes to request (comma-separated) - redirect_url: Optional URL to redirect to after authorization completes # Authorize Linkedin Source: https://docs.klavis.ai/api-reference/linkedin-oauth/authorize-linkedin get /oauth/linkedin/authorize Start LinkedIn OAuth flow Parameters: - instance_id: Identifier for the instance requesting authorization - client_id: Optional client ID for white labeling - scope: Optional scopes to request (comma-separated) - redirect_url: Optional URL to redirect to after authorization completes # Call Tool Source: https://docs.klavis.ai/api-reference/mcp-server/call-tool post /mcp-server/call-tool Calls a tool on a specific remote MCP server, used for function calling. Eliminates the need for manual MCP code implementation. Under the hood, Klavis will instantiates an MCP client and establishes a connection with the remote MCP server to call the tool. # Create a Server Instance Source: https://docs.klavis.ai/api-reference/mcp-server/create-a-server-instance post /mcp-server/instance/create Creates a URL for a specified MCP server, validating the request with an API key and user details. Returns the existing server URL if it already exists for the user. If OAuth is configured for the server, also returns the base OAuth authorization URL. # Delete a Server Instance Source: https://docs.klavis.ai/api-reference/mcp-server/delete-a-server-instance delete /mcp-server/instance/delete/{instance_id} Completely removes a server connection instance using its unique ID, deleting all associated data from the system. # Delete Auth data for a Server Instance Source: https://docs.klavis.ai/api-reference/mcp-server/delete-auth-data-for-a-server-instance delete /mcp-server/instance/delete-auth/{instance_id} Deletes authentication metadata for a specific server connection instance. # Get All Servers Source: https://docs.klavis.ai/api-reference/mcp-server/get-all-servers get /mcp-server/servers Get all MCP servers with their basic information including id, name, description, and tools. # Get Authentication Metadata Source: https://docs.klavis.ai/api-reference/mcp-server/get-auth-metadata get /mcp-server/instance/get-auth/{instance_id} Retrieves the auth metadata for a specific instance that the API key owner controls. Includes access token, refresh token, and other authentication metadata. This endpoint includes proper ownership verification to ensure users can only access authentication data for instances they own. It also handles token refresh if needed. # Get OAuth URL Source: https://docs.klavis.ai/api-reference/mcp-server/get-oauth-url post /mcp-server/oauth-url Gets the OAuth authorization URL for a specific MCP server and instance. Returns the complete OAuth URL with the instance ID as a query parameter. # Get Server Instance Source: https://docs.klavis.ai/api-reference/mcp-server/get-server-instance get /mcp-server/instance/get/{instance_id} Checks the details of a specific server connection instance using its unique ID and API key, returning server details like authentication status and associated server/platform info. # Get Tools Source: https://docs.klavis.ai/api-reference/mcp-server/get-tools get /mcp-server/tools/{server_name} Get list of tool names for a specific MCP server. Mainly used for querying metadata about the MCP server. # List Tools Source: https://docs.klavis.ai/api-reference/mcp-server/list-tools post /mcp-server/list-tools Lists all tools available for a specific remote MCP server in various AI model formats. This eliminates the need for manual MCP code implementation and format conversion. Under the hood, Klavis instantiates an MCP client and establishes a connection with the remote MCP server to retrieve available tools. # Set Auth Token Source: https://docs.klavis.ai/api-reference/mcp-server/set-auth-token post /mcp-server/instance/set-auth-token Sets an authentication token for a specific instance. This updates the auth_metadata for the specified instance. # Authorize Notion Source: https://docs.klavis.ai/api-reference/notion-oauth/authorize-notion get /oauth/notion/authorize Start Notion OAuth flow Parameters: - instance_id: Identifier for the instance requesting authorization - client_id: Optional client ID for white labeling - scope: Optional scopes to request (comma-separated) - redirect_url: Optional URL to redirect to after authorization completes # Authorize Salesforce Source: https://docs.klavis.ai/api-reference/salesforce-oauth/authorize-salesforce get /oauth/salesforce/authorize Start Salesforce OAuth flow Parameters: - instance_id: Identifier for the instance requesting authorization - client_id: Optional client ID for white labeling - scope: Optional scopes to request (space-separated) - redirect_url: Optional URL to redirect to after authorization completes - instance_url: Optional Salesforce instance URL for sandbox or custom domains # Authorize Slack Source: https://docs.klavis.ai/api-reference/slack-oauth/authorize-slack get /oauth/slack/authorize Start Slack OAuth flow Parameters: - instance_id: Identifier for the instance requesting authorization - client_id: Optional client ID for white labeling - scope: Optional scopes to request (comma-separated) - user_scope: Optional user-specific scopes to request (comma-separated) - redirect_url: Optional URL to redirect to after authorization completes # Authorize Supabase Source: https://docs.klavis.ai/api-reference/supabase-oauth/authorize-supabase get /oauth/supabase/authorize Start Supabase OAuth flow Parameters: - instance_id: Identifier for the instance requesting authorization - client_id: Optional client ID for white labeling - redirect_url: Optional URL to redirect to after authorization completes # Get user instances Source: https://docs.klavis.ai/api-reference/user/get-server-instances get /user/instances Get all MCP server instances information by user ID and platform name. # Create Source: https://docs.klavis.ai/api-reference/white-labeling/create post /white-labeling/create Saves OAuth white labeling information, or updates existing information if the `client_id` matches. # Get Source: https://docs.klavis.ai/api-reference/white-labeling/get get /white-labeling/get/{client_id} Retrieves white labeling information for a specific OAuth client ID. # Authorize Wordpress Source: https://docs.klavis.ai/api-reference/wordpress-oauth/authorize-wordpress get /oauth/wordpress/authorize Start WordPress OAuth flow Parameters: - instance_id: Identifier for the instance requesting authorization - client_id: Optional client ID for white labeling - scope: Optional scopes to request (comma-separated) - redirect_url: Optional URL to redirect to after authorization completes # Develop with AI Source: https://docs.klavis.ai/develop-with-ai Make your coding assistant access Klavis documentation. Klavis provides LLM-accessible tools (powered by Mintlify) that you can plug locally in your coding assistant (Cursor, Windsurf, Claude Desktop, etc.) to speed up your local development. There are two options: * **An MCP server** that can directly query this documentation, ensuring your coding assistant receives real-time information about available commands and features. * **An llms-full.txt** text file with the entire documentation compiled and formatted for LLMs Alternatively you can also use the native AI assistant built into this documentation portal. ## Option 1: Install the MCP server Open a terminal and run the following command to install the MCP server locally: ```bash npx mint-mcp add klavisai ``` Everything will be set up automatically. Klavis MCP Server Setup ## Option 2: Copy-paste llms-full.txt You'll find a `llms-full.txt` file at the root level of this documentation. It is a compiled text document designed to provide context for LLMs. Copy the following content and paste it in the prompt for your coding assistant: [https://docs.klavis.ai/llms-full.txt](https://docs.klavis.ai/llms-full.txt) ## Option 3: Use the documentation's built-in assistant This documentation portal has a built-in AI assistant. Simply click "✨**Ask AI**" at the top of any page to use it. Ask AI Assistant # Claude Source: https://docs.klavis.ai/documentation/ai-platform-integration/claude Learn how to build AI agents that integrate Anthropic's Claude with Klavis MCP Servers for enhanced functionality [![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) # Claude + Klavis AI Integration This tutorial demonstrates how to use Anthropic's Claude with tool use (function calling) with Klavis MCP (Model Context Protocol) servers. ## 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 pip install anthropic klavis ``` ```bash TypeScript npm install @anthropic-ai/sdk klavis ``` ## Setup Environment Variables ```python Python import os import json from anthropic import Anthropic from klavis import Klavis from klavis.types import McpServerName, ToolFormat # Set environment variables 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 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 ``` ## Case Study 1: Claude + YouTube MCP Server ### Step 1 - Create YouTube MCP Server using Klavis ```python Python klavis_client = Klavis(api_key=os.getenv("KLAVIS_API_KEY")) youtube_mcp_instance = klavis_client.mcp_server.create_server_instance( server_name=McpServerName.YOUTUBE, user_id="1234", platform_name="Klavis", ) # print(f"πŸ”— YouTube MCP server created at: {youtube_mcp_instance.server_url}, and the instance id is {youtube_mcp_instance.instance_id}") ``` ```typescript TypeScript const klavisClient = new KlavisClient({ apiKey: process.env.KLAVIS_API_KEY }); const youtubeMcpInstance = await klavisClient.mcpServer.createServerInstance({ serverName: Klavis.McpServerName.Youtube, userId: "1234", platformName: "Klavis" }); // console.log(`πŸ”— YouTube MCP server created at: ${youtubeMcpInstance.serverUrl}, and the instance id is ${youtubeMcpInstance.instanceId}`); ``` ### Step 2 - Create general method to use MCP Server with Claude ```python Python 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, ) response = claude_client.messages.create( model="claude-3-5-sonnet-20241022", 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}) final_response = claude_client.messages.create( model="claude-3-5-sonnet-20241022", 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 ) return final_response.content[0].text else: return response.content[0].text ``` ```typescript TypeScript 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 response = await claudeClient.messages.create({ model: "claude-3-5-sonnet-20241022", 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 }); const finalResponse = await claudeClient.messages.create({ model: "claude-3-5-sonnet-20241022", max_tokens: 4000, system: "You are a helpful assistant. Use the available tools to answer the user's question.", messages: messages, tools: mcpServerTools.tools }); return finalResponse.content[0].text; } else { return response.content[0].text; } } ``` ### Step 3 - Summarize your favorite video! ```python Python YOUTUBE_VIDEO_URL = "https://www.youtube.com/watch?v=LCEmiRjPEtQ" # pick a video you like! result = claude_with_mcp_server( mcp_server_url=youtube_mcp_instance.server_url, user_query=f"Summarize this YouTube video with timestamps: {YOUTUBE_VIDEO_URL}" ) print(result) ``` ```typescript TypeScript const YOUTUBE_VIDEO_URL = "https://www.youtube.com/watch?v=LCEmiRjPEtQ"; // pick a video you like! const result = await claudeWithMcpServer( youtubeMcpInstance.serverUrl, `Summarize this YouTube video with timestamps: ${YOUTUBE_VIDEO_URL}` ); console.log(result); ``` βœ… Great! You've successfully created an AI agent that uses Claude's tool use with Klavis MCP servers to summarize YouTube videos! ## Case Study 2: Claude + Gmail MCP Server (OAuth needed) ```python Python import webbrowser gmail_mcp_server = klavis_client.mcp_server.create_server_instance( server_name=McpServerName.GMAIL, user_id="1234", platform_name="Klavis", ) webbrowser.open(gmail_mcp_server.oauth_url) print(f"πŸ” Opening OAuth authorization for Gmail, if you are not redirected, please open the following URL in your browser: {gmail_mcp_server.oauth_url}") ``` ```typescript TypeScript const gmailMcpServer = await klavisClient.mcpServer.createServerInstance({ serverName: Klavis.McpServerName.Gmail, userId: "1234", platformName: "Klavis" }); // In a web environment, you might redirect the user window.open(gmailMcpServer.oauthUrl); console.log(`πŸ” Opening OAuth authorization for Gmail, if you are not redirected, please open the following URL in your browser: ${gmailMcpServer.oauthUrl}`); ``` After completing the OAuth authorization, you can send emails using the agent. ```python Python EMAIL_RECIPIENT = "zihaolin@klavis.ai" # Replace with your email EMAIL_SUBJECT = "Test Claude + Gmail MCP Server" EMAIL_BODY = "Hello World from Claude!" result = claude_with_mcp_server( mcp_server_url=gmail_mcp_server.server_url, user_query=f"Please send an email to {EMAIL_RECIPIENT} with subject {EMAIL_SUBJECT} and body {EMAIL_BODY}" ) print(result) ``` ```typescript TypeScript const EMAIL_RECIPIENT = "zihaolin@klavis.ai"; // Replace with your email const EMAIL_SUBJECT = "Test Claude + Gmail MCP Server"; const EMAIL_BODY = "Hello World from Claude!"; const result = await claudeWithMcpServer( gmailMcpServer.serverUrl, `Please send an email to ${EMAIL_RECIPIENT} with subject ${EMAIL_SUBJECT} and body ${EMAIL_BODY}` ); console.log(result); ``` ## Summary This tutorial demonstrated how to integrate Anthropic's Claude with tool use capabilities with Klavis MCP servers to create powerful AI applications. We covered two practical examples: **πŸŽ₯ YouTube Integration**: Built an AI assistant that can automatically summarize YouTube videos by extracting transcripts and providing detailed, timestamped summaries. **πŸ“§ Gmail Integration**: Created an AI-powered email assistant that can send emails through Gmail with OAuth authentication. ### Key Takeaways: * **Easy Setup**: Klavis MCP servers can be created with just a few lines of code * **Claude Compatible**: All tools are formatted for seamless Claude tool use * **Versatile**: Support for both simple APIs (YouTube) and OAuth-authenticated services (Gmail) * **Scalable**: The same pattern can be applied to any of the MCP servers available in Klavis * **Advanced Reasoning**: Claude's superior reasoning capabilities make it excellent for complex analysis tasks ## Next Steps Try other available servers like Slack, Notion, GitHub, etc. Build multi-step workflows combining multiple MCP servers Scale these patterns for production applications Build custom MCP servers for your specific needs ## Useful Resources * [Anthropic Documentation](https://docs.anthropic.com/) * [Claude API Reference](https://docs.anthropic.com/claude/reference/) * [Klavis AI Documentation](https://docs.klavis.ai/) * [MCP Protocol Specification](https://modelcontextprotocol.io/) * [Klavis MCP Servers](/documentation/mcp-server) **Happy building!** πŸš€ # CrewAI Source: https://docs.klavis.ai/documentation/ai-platform-integration/crewai Build powerful AI agent crews that integrate CrewAI with Klavis MCP Servers for multi-agent workflows ## 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 pip install crewai 'crewai-tools[mcp]' klavis openai ``` ```bash TypeScript npm install crewai crewai-tools klavis openai ``` ## Setup Environment Variables ```python Python 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 // 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 ## Use Case Examples ### Example 1: YouTube Research Crew Create a specialized agent that can research and analyze YouTube videos. Set up CrewAI + Klavis integration Create a YouTube MCP server instance Create an agent specialized in video content analysis Run the crew to analyze a YouTube video ```python Python from crewai import Agent, Task, Crew, Process from crewai_tools import MCPServerAdapter from klavis import Klavis from klavis.types import McpServerName # Initialize clients klavis_client = Klavis(api_key=os.getenv("KLAVIS_API_KEY")) # Create YouTube MCP server youtube_mcp_instance = klavis_client.mcp_server.create_server_instance( server_name=McpServerName.YOUTUBE, user_id="1234", platform_name="Klavis", ) print(f"πŸ”— YouTube MCP server created at: {youtube_mcp_instance.server_url}") # Configure MCP server parameters for CrewAI server_params = { "url": youtube_mcp_instance.server_url, "transport": "streamable-http" } YOUTUBE_VIDEO_URL = "https://www.youtube.com/watch?v=LCEmiRjPEtQ" try: with MCPServerAdapter(server_params) as mcp_tools: print(f"βœ… Available tools: {[tool.name for tool in mcp_tools]}") # Create a YouTube Analysis Agent youtube_agent = Agent( role="YouTube Content Analyst", goal="Research and analyze YouTube videos to extract comprehensive insights", backstory="You are an expert at analyzing video content and creating professional summaries.", tools=mcp_tools, reasoning=True, verbose=False ) # Define Task analysis_task = Task( description=f"Research the YouTube video at {YOUTUBE_VIDEO_URL}. Extract the video transcript, analyze the content, and create a comprehensive summary with key points, timestamps, and main takeaways.", expected_output="Complete video analysis with transcript, structured summary, key insights, timestamps, and main takeaways", agent=youtube_agent, markdown=True ) # Create and execute the crew youtube_crew = Crew( agents=[youtube_agent], tasks=[analysis_task], verbose=False, process=Process.sequential ) result = youtube_crew.kickoff() print(result) except Exception as e: print(f"❌ Error connecting to YouTube MCP server: {e}") ``` ```typescript TypeScript import { CrewAI, Agent, Task, Crew } from 'crewai'; import { MCPServerAdapter } from 'crewai-tools'; import { KlavisClient, Klavis } from 'klavis'; // Initialize clients const klavisClient = new KlavisClient({ apiKey: process.env.KLAVIS_API_KEY }); // Create YouTube MCP server const youtubeMcpInstance = await klavisClient.mcpServer.createServerInstance({ serverName: Klavis.McpServerName.Youtube, userId: "1234", platformName: "Klavis", }); console.log(`πŸ”— YouTube MCP server created at: ${youtubeMcpInstance.serverUrl}`); // Configure MCP server parameters for CrewAI const serverParams = { url: youtubeMcpInstance.serverUrl, transport: "streamable-http" }; const YOUTUBE_VIDEO_URL = "https://www.youtube.com/watch?v=LCEmiRjPEtQ"; try { const mcpTools = new MCPServerAdapter(serverParams); console.log(`βœ… Available tools connected`); // Create a YouTube Analysis Agent const youtubeAgent = new Agent({ role: "YouTube Content Analyst", goal: "Research and analyze YouTube videos to extract comprehensive insights", backstory: "You are an expert at analyzing video content and creating professional summaries.", tools: mcpTools, reasoning: true, verbose: false }); // Define Task const analysisTask = new Task({ description: `Research the YouTube video at ${YOUTUBE_VIDEO_URL}. Extract the video transcript, analyze the content, and create a comprehensive summary with key points, timestamps, and main takeaways.`, expectedOutput: "Complete video analysis with transcript, structured summary, key insights, timestamps, and main takeaways", agent: youtubeAgent, markdown: true }); // Create and execute the crew const youtubeCrew = new Crew({ agents: [youtubeAgent], tasks: [analysisTask], verbose: false, process: CrewAI.Process.Sequential }); const result = await youtubeCrew.kickoff(); console.log(result); } catch (error) { console.error(`❌ Error connecting to YouTube MCP server: ${error}`); } ``` ### Example 2: Multi-Service Research & Communication Crew Create a two-agent crew that researches content and communicates findings via email. Gmail integration requires OAuth authentication, so you'll need to authorize the application in your browser. Set up both YouTube and Gmail MCP servers Complete OAuth flow for Gmail access Set up research agent and communication agent Run the sequential workflow ```python Python import webbrowser # Create YouTube and Gmail MCP servers youtube_mcp_instance = klavis_client.mcp_server.create_server_instance( server_name=McpServerName.YOUTUBE, user_id="1234", platform_name="Klavis", ) gmail_mcp_instance = klavis_client.mcp_server.create_server_instance( server_name=McpServerName.GMAIL, user_id="1234", platform_name="Klavis", ) # Handle OAuth for Gmail webbrowser.open(gmail_mcp_instance.oauth_url) print(f"πŸ” Opening OAuth authorization for Gmail...") print(f"πŸ“± If not redirected automatically, open: {gmail_mcp_instance.oauth_url}") VIDEO_URL = "https://www.youtube.com/watch?v=LCEmiRjPEtQ" RECIPIENT_EMAIL = "your-email@example.com" # Configure multiple MCP servers multiple_server_params = [ { "url": youtube_mcp_instance.server_url, "transport": "streamable-http" }, { "url": gmail_mcp_instance.server_url, "transport": "streamable-http" } ] try: with MCPServerAdapter(multiple_server_params) as all_mcp_tools: print(f"βœ… Available tools from all MCP servers: {[tool.name for tool in all_mcp_tools]}") # Create YouTube Research Agent youtube_research_agent = Agent( role="YouTube Content Analyst", goal="Research and analyze YouTube videos to extract comprehensive insights", backstory="You are an expert at analyzing video content and extracting key insights.", tools=all_mcp_tools, reasoning=False, verbose=False, ) # Create Email Communication Agent email_agent = Agent( role="Email Communications Specialist", goal="Draft and send professional email communications based on research findings", backstory="You are skilled at crafting professional emails with clear, impactful messaging.", tools=all_mcp_tools, reasoning=True, verbose=False, ) # Define workflow tasks youtube_research_task = Task( description=f"Research the YouTube video at {VIDEO_URL}. Extract transcript, analyze the content for key insights about AI and software development, and create a comprehensive analysis report with key takeaways and recommendations.", expected_output="Complete video analysis report with transcript, key insights, recommendations, and strategic takeaways", agent=youtube_research_agent ) send_email_task = Task( description=f"Based on the youtube analysis, draft and send a professional email to {RECIPIENT_EMAIL} with the subject 'YouTube Video AI Analysis'. Include content of the youtube video in the email.", expected_output="Confirmation that a professional email has been sent with the research insights", agent=email_agent, context=[youtube_research_task] ) # Create and execute the crew multi_service_crew = Crew( agents=[youtube_research_agent, email_agent], tasks=[youtube_research_task, send_email_task], verbose=False, process=Process.sequential ) result = multi_service_crew.kickoff() print(result) except Exception as e: print(f"❌ Error with multi-service MCP integration: {e}") ``` ```typescript TypeScript // Create YouTube and Gmail MCP servers const youtubeMcpInstance = await klavisClient.mcpServer.createServerInstance({ serverName: Klavis.McpServerName.Youtube, userId: "1234", platformName: "Klavis", }); const gmailMcpInstance = await klavisClient.mcpServer.createServerInstance({ serverName: Klavis.McpServerName.Gmail, userId: "1234", platformName: "Klavis", }); // Handle OAuth for Gmail console.log(f"πŸ” Opening OAuth authorization for Gmail..."); console.log(f"πŸ“± Please open: {gmailMcpInstance.oauthUrl}"); const VIDEO_URL = "https://www.youtube.com/watch?v=LCEmiRjPEtQ"; const RECIPIENT_EMAIL = "your-email@example.com"; // Configure multiple MCP servers const multipleServerParams = [ { url: youtubeMcpInstance.serverUrl, transport: "streamable-http" }, { url: gmailMcpInstance.serverUrl, transport: "streamable-http" } ]; try { const allMcpTools = new MCPServerAdapter(multipleServerParams); console.log(`βœ… Available tools from all MCP servers connected`); // Create YouTube Research Agent const youtubeResearchAgent = new Agent({ role: "YouTube Content Analyst", goal: "Research and analyze YouTube videos to extract comprehensive insights", backstory: "You are an expert at analyzing video content and extracting key insights.", tools: allMcpTools, reasoning: false, verbose: false, }); // Create Email Communication Agent const emailAgent = new Agent({ role: "Email Communications Specialist", goal: "Draft and send professional email communications based on research findings", backstory: "You are skilled at crafting professional emails with clear, impactful messaging.", tools: allMcpTools, reasoning: true, verbose: false, }); // Define workflow tasks const youtubeResearchTask = new Task({ description: `Research the YouTube video at ${VIDEO_URL}. Extract transcript, analyze the content for key insights about AI and software development, and create a comprehensive analysis report with key takeaways and recommendations.`, expectedOutput: "Complete video analysis report with transcript, key insights, recommendations, and strategic takeaways", agent: youtubeResearchAgent }); const sendEmailTask = new Task({ description: `Based on the youtube analysis, draft and send a professional email to ${RECIPIENT_EMAIL} with the subject 'YouTube Video AI Analysis'. Include content of the youtube video in the email.`, expectedOutput: "Confirmation that a professional email has been sent with the research insights", agent: emailAgent, context: [youtubeResearchTask] }); // Create and execute the crew const multiServiceCrew = new Crew({ agents: [youtubeResearchAgent, emailAgent], tasks: [youtubeResearchTask, sendEmailTask], verbose: false, process: CrewAI.Process.Sequential }); const result = await multiServiceCrew.kickoff(); console.log(result); } catch (error) { console.error(`❌ Error with multi-service MCP integration: ${error}`); } ``` ## Security Best Practices When using CrewAI with Klavis MCP servers, follow these security guidelines: ```python Python 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 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 YouTube research agent and expand from there! πŸš€πŸ‘₯ # Fireworks AI Source: https://docs.klavis.ai/documentation/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 pip install fireworks-ai klavis ``` ```bash TypeScript npm install fireworks-ai klavis ``` ## Setup Environment Variables ```python Python 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 // 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 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 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 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 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 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", platform_name="Klavis", ) # 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 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", platformName: "Klavis", }); // 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 import webbrowser # Create Gmail MCP server instance gmail_mcp_instance = klavis_client.mcp_server.create_server_instance( server_name=McpServerName.GMAIL, user_id="1234", platform_name="Klavis", ) # 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 // Create Gmail MCP server instance const gmailMcpInstance = await klavisClient.mcpServer.createServerInstance({ serverName: Klavis.McpServerName.Gmail, userId: "1234", platformName: "Klavis", }); // 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://docs.klavis.ai/) * [MCP Protocol Specification](https://modelcontextprotocol.io/) * [Klavis MCP Servers](/documentation/mcp-server) **Happy building with Fireworks AI and Klavis!** πŸš€ # Gemini Source: https://docs.klavis.ai/documentation/ai-platform-integration/gemini Learn how to build AI agents that integrate Google's Gemini with Klavis MCP Servers for multimodal AI capabilities [![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 pip install google-genai klavis ``` ```bash TypeScript npm install @google/genai klavis ``` ## Full Code Examples For complete working examples, check out the source code: ## Setup Environment Variables ```python Python import os import webbrowser from google import genai from google.genai import types from klavis import Klavis from klavis.types import McpServerName, ToolFormat # Set environment variables (you can also use .env file) 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 # Initialize clients gemini_client = genai.Client(api_key=os.getenv("GEMINI_API_KEY")) klavis_client = Klavis(api_key=os.getenv("KLAVIS_API_KEY")) ``` ```typescript TypeScript import { GoogleGenAI, ToolListUnion } from '@google/genai'; import { KlavisClient, Klavis } from 'klavis'; import open from 'open'; // Set your API keys here const geminiApiKey = "YOUR_GEMINI_API_KEY"; // Replace with your actual Gemini API key const klavisApiKey = "YOUR_KLAVIS_API_KEY"; // Replace with your actual Klavis API key const geminiClient = new GoogleGenAI({ apiKey: geminiApiKey }); const klavisClient = new KlavisClient({ apiKey: klavisApiKey }); ``` ## Case Study 1: Gemini + YouTube MCP Server ### Step 1 - Create YouTube MCP Server using Klavis ```python Python youtube_mcp_instance = klavis_client.mcp_server.create_server_instance( server_name=McpServerName.YOUTUBE, user_id="1234", platform_name="Klavis", ) print(f"πŸ”— YouTube MCP server created at: {youtube_mcp_instance.server_url}, and the instance id is {youtube_mcp_instance.instance_id}") ``` ```typescript TypeScript const youtubeMcpInstance = await klavisClient.mcpServer.createServerInstance({ serverName: Klavis.McpServerName.Youtube, userId: "1234", platformName: "Klavis", }); console.log(`πŸ”— YouTube MCP server created at: ${youtubeMcpInstance.serverUrl}, and the instance id is ${youtubeMcpInstance.instanceId}`); ``` ### Step 2 - Create general method to use MCP Server with Gemini ```python Python def gemini_with_mcp_server(mcp_server_url: str, user_query: str): # Get tools from MCP server mcp_server_tools = klavis_client.mcp_server.list_tools( server_url=mcp_server_url, format=ToolFormat.GEMINI, ) # Prepare conversation contents contents = [types.Content(role="user", parts=[types.Part(text=user_query)])] # Generate response with function calling response = gemini_client.models.generate_content( model='gemini-1.5-pro', 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 print(f"πŸ”§ Calling function: {part.function_call.name}") try: # Execute tool call via Klavis function_result = klavis_client.mcp_server.call_tools( server_url=mcp_server_url, tool_name=part.function_call.name, tool_args=dict(part.function_call.args), ) # Create function response in the proper format function_response = {'result': function_result.result} except Exception as e: print(f"Function call error: {e}") function_response = {'error': str(e)} # Add function response to conversation function_response_part = types.Part.from_function_response( name=part.function_call.name, response=function_response, ) function_response_content = types.Content( role='tool', parts=[function_response_part] ) contents.append(function_response_content) if has_function_calls: # Generate final response after function calls final_response = gemini_client.models.generate_content( model='gemini-1.5-pro', contents=contents, config=types.GenerateContentConfig(tools=mcp_server_tools.tools) ) return final_response.text else: # No function calls, return original response return response.text else: return "No response generated." ``` ```typescript TypeScript async function geminiWithMcpServer(mcpServerUrl: string, userQuery: string) { // Get tools from MCP server const mcpTools = await klavisClient.mcpServer.listTools({ serverUrl: mcpServerUrl, format: Klavis.ToolFormat.Gemini }); const contents: any[] = []; // Extract function declarations from the Klavis response const gemini_tools = mcpTools.tools as ToolListUnion; const functionDeclarations = (gemini_tools[0] as any)?.function_declarations || []; contents.push({ role: "user", parts: [{ text: userQuery }] }); const response = await geminiClient.models.generateContent({ model: 'gemini-2.5-flash', contents: contents, config: { tools: [{ functionDeclarations: functionDeclarations }], } }); if (!response.candidates || !response.candidates[0]?.content?.parts) { return "No response generated."; } contents.push(response.candidates[0].content); // Check for function calls in the response let hasFunctionCalls = false; const functionCallResults: any[] = []; // Check if response has functionCalls property if (response.functionCalls && response.functionCalls.length > 0) { hasFunctionCalls = true; for (const functionCall of response.functionCalls) { console.log(`πŸ”§ Calling function: ${functionCall.name}`); try { // Execute tool call via Klavis const functionResult = await klavisClient.mcpServer.callTools({ serverUrl: mcpServerUrl, toolName: functionCall.name || '', toolArgs: functionCall.args || {}, }); functionCallResults.push({ functionResponse: { name: functionCall.name, response: functionResult.result } }); } catch (error) { console.error(`❌ Function call error: ${error}`); functionCallResults.push({ functionResponse: { name: functionCall.name, response: { error: String(error) } } }); } } } // If there were function calls, add the results and get final response if (hasFunctionCalls && functionCallResults.length > 0) { // Add function responses to conversation history contents.push({ role: 'tool', parts: functionCallResults }); // Get final response after function execution const finalResponse = await geminiClient.models.generateContent({ model: 'gemini-2.5-flash', contents: contents, config: { tools: [{ functionDeclarations: functionDeclarations }], temperature: 0, } }); return finalResponse.text || 'No response text'; } else { // No function calls, just display the response return response.text || 'No response text'; } } ``` ### Step 3 - Summarize your favorite video! ```python Python YOUTUBE_VIDEO_URL = "https://www.youtube.com/watch?v=LCEmiRjPEtQ" # pick a video you like! result = gemini_with_mcp_server( mcp_server_url=youtube_mcp_instance.server_url, user_query=f"Please provide a complete summary of this YouTube video with timestamp: {YOUTUBE_VIDEO_URL}" ) print(result) ``` ```typescript TypeScript const YOUTUBE_VIDEO_URL = "https://www.youtube.com/watch?v=LCEmiRjPEtQ"; // pick a video you like! const result = await geminiWithMcpServer( youtubeMcpInstance.serverUrl, `Please provide a complete summary of this YouTube video with timestamp: ${YOUTUBE_VIDEO_URL}` ); console.log(result); ``` βœ… Great! You've successfully created an AI agent that uses Gemini's function calling with Klavis MCP servers to summarize YouTube videos! ## Case Study 2: Gemini + Gmail MCP Server (OAuth needed) ```python Python # Create Gmail MCP server instance gmail_mcp_server = klavis_client.mcp_server.create_server_instance( server_name=McpServerName.GMAIL, user_id="1234", platform_name="Klavis", ) # Redirect to Gmail OAuth page for authorization webbrowser.open(gmail_mcp_server.oauth_url) print(f"πŸ” Opening OAuth authorization for Gmail, if you are not redirected, please open the following URL in your browser: {gmail_mcp_server.oauth_url}") ``` ```typescript TypeScript // Create Gmail MCP server instance const gmailMcpServer = await klavisClient.mcpServer.createServerInstance({ serverName: Klavis.McpServerName.Gmail, userId: "1234", platformName: "Klavis", }); // Handle OAuth if needed if (gmailMcpServer.oauthUrl) { console.log(`πŸ” Opening OAuth authorization: ${gmailMcpServer.oauthUrl}`); await open(gmailMcpServer.oauthUrl); console.log("Please complete the OAuth authorization in your browser..."); } ``` ```python Python EMAIL_RECIPIENT = "zihaolin@klavis.ai" # Replace with your email EMAIL_SUBJECT = "Test Gemini + Gmail MCP Server" EMAIL_BODY = "Hello World from Gemini!" result = gemini_with_mcp_server( mcp_server_url=gmail_mcp_server.server_url, user_query=f"Please send an email to {EMAIL_RECIPIENT} with subject {EMAIL_SUBJECT} and body {EMAIL_BODY}" ) print(result) ``` ```typescript TypeScript const EMAIL_RECIPIENT = "zihaolin@klavis.ai"; // Replace with your email const EMAIL_SUBJECT = "Test Gemini + Gmail MCP Server"; const EMAIL_BODY = "Hello World from Gemini!"; const result = await geminiWithMcpServer( gmailMcpServer.serverUrl, `Please send an email to ${EMAIL_RECIPIENT} with subject ${EMAIL_SUBJECT} and body ${EMAIL_BODY}` ); console.log(result); ``` ## Summary This tutorial demonstrated how to integrate Google's Gemini with function calling capabilities with Klavis MCP servers to create powerful AI applications. We covered two practical examples: **πŸŽ₯ YouTube Integration**: Built an AI assistant that can automatically summarize YouTube videos by extracting transcripts and providing detailed, timestamped summaries. **πŸ“§ Gmail Integration**: Created an AI-powered email assistant that can send emails through Gmail with OAuth authentication. ## 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://docs.klavis.ai/) * [MCP Protocol Specification](https://modelcontextprotocol.io/) * [Klavis MCP Servers](/documentation/mcp-server) **Happy building!** πŸš€ # LangChain Source: https://docs.klavis.ai/documentation/ai-platform-integration/langchain Learn how to build multi-agent workflows using LangChain's agent framework with Klavis MCP Servers ## Prerequisites Before we begin, you'll need: Get your API key from OpenAI Platform (LangChain uses OpenAI as the default LLM) Get your API key from Klavis AI ## Installation First, install the required packages: ```bash Python pip install langchain-mcp-adapters langgraph langchain-openai klavis ``` ```bash TypeScript npm install @langchain/mcp-adapters @langchain/langgraph @langchain/openai klavis ``` ## Setup Environment Variables ```python Python 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 // 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 import os import asyncio from klavis import Klavis from klavis.types import McpServerName from langchain_mcp_adapters.client import MultiServerMCPClient from langgraph.prebuilt import create_react_agent from langchain_openai import ChatOpenAI # Initialize clients klavis_client = Klavis(api_key=os.getenv("KLAVIS_API_KEY")) llm = ChatOpenAI(model="gpt-4o-mini", api_key=os.getenv("OPENAI_API_KEY")) ``` ```typescript TypeScript import { KlavisClient, Klavis } from 'klavis'; import { MultiServerMCPClient } from "@langchain/mcp-adapters"; import { ChatOpenAI } from "@langchain/openai"; import { createReactAgent } from "@langchain/langgraph/prebuilt"; // Initialize clients const klavisClient = new KlavisClient({ apiKey: process.env.KLAVIS_API_KEY }); const llm = new ChatOpenAI({ modelName: "gpt-4o-mini", apiKey: process.env.OPENAI_API_KEY }); ``` ## Single MCP Server Integration Let's start with creating a simple AI agent that can summarize YouTube videos using LangChain and a single Klavis MCP Server. ### Step 1: Create MCP Server Instance ```python Python # Create a YouTube MCP server and get the server URL youtube_mcp_instance = klavis_client.mcp_server.create_server_instance( server_name=McpServerName.YOUTUBE, user_id="1234", platform_name="klavis", ) youtube_mcp_server_url = youtube_mcp_instance.server_url print(f"πŸ”— YouTube MCP server created at: {youtube_mcp_server_url}") ``` ```typescript TypeScript // Create a YouTube MCP server and get the server URL const youtubeMcpInstance = await klavisClient.mcpServer.createServerInstance({ serverName: Klavis.McpServerName.Youtube, userId: "1234", platformName: "Klavis", }); const youtubeMcpServerUrl = youtubeMcpInstance.serverUrl; console.log(`πŸ”— YouTube MCP server created at: ${youtubeMcpServerUrl}`); ``` ### Step 2: Create LangChain Agent with MCP Tools ```python Python # Create MCP client with YouTube server mcp_client = MultiServerMCPClient({ "youtube": { "transport": "streamable_http", "url": youtube_mcp_server_url } }) # Get tools from MCP server tools = asyncio.run(mcp_client.get_tools()) # Create agent with MCP-based tools youtube_agent = create_react_agent( model=llm, tools=tools, prompt="You are an AI assistant that uses MCP tools to analyze YouTube videos." ) print("πŸ€– YouTube AI agent created successfully!") ``` ```typescript TypeScript // Create MCP client with YouTube server const mcpClient = new MultiServerMCPClient({ throwOnLoadError: true, useStandardContentBlocks: true, mcpServers: { youtube: { url: youtubeMcpServerUrl, transport: "streamable_http" } } }); // Get tools from MCP server const tools = await mcpClient.getTools(); // Create agent with MCP-based tools const youtubeAgent = createReactAgent({ llm: llm, tools: tools, systemMessage: "You are an AI assistant that uses MCP tools to analyze YouTube videos." }); console.log("πŸ€– YouTube AI agent created successfully!"); ``` ### Step 3: Use the Agent ```python Python YOUTUBE_VIDEO_URL = "https://www.youtube.com/watch?v=LCEmiRjPEtQ" # pick a video you like! response = asyncio.run(youtube_agent.ainvoke({ "messages": [{"role": "user", "content": f"Summarize this video: {YOUTUBE_VIDEO_URL}"}] })) print("βœ… Video Summary:", response["messages"][-1].content) ``` ```typescript TypeScript const YOUTUBE_VIDEO_URL = "https://www.youtube.com/watch?v=MmiveeGxfX0"; // pick a video you like! try { const response = await youtubeAgent.invoke({ messages: [{ role: "user", content: `Summarize this video: ${YOUTUBE_VIDEO_URL}` }] }); console.log("βœ… Video Summary:", response); } catch (error) { console.error("Error during agent execution:", error); if (error.name === "ToolException") { console.error("Tool execution failed:", error.message); } } finally { await mcpClient.close(); } ``` ## Multiple MCP Servers Integration Now let's build a more sophisticated multi-agent workflow that summarizes YouTube videos and sends the summary via email using multiple MCP servers. ### Step 1: Create Multiple MCP Server Instances ```python Python import webbrowser # Create YouTube MCP server youtube_mcp_instance = klavis_client.mcp_server.create_server_instance( server_name=McpServerName.YOUTUBE, user_id="1234", platform_name="klavis", ) # Create Gmail MCP server with OAuth authorization gmail_mcp_instance = klavis_client.mcp_server.create_server_instance( server_name=McpServerName.GMAIL, user_id="1234", platform_name="klavis", ) print("βœ… Created YouTube and Gmail MCP instances") # Open Gmail OAuth authorization 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}") ``` ```typescript TypeScript // Create YouTube MCP server const youtubeMcpInstance = await klavisClient.mcpServer.createServerInstance({ serverName: Klavis.McpServerName.Youtube, userId: "1234", platformName: "Klavis", }); // Create Gmail MCP server with OAuth authorization const gmailMcpInstance = await klavisClient.mcpServer.createServerInstance({ serverName: Klavis.McpServerName.Gmail, userId: "1234", platformName: "Klavis", }); console.log("βœ… Created YouTube and Gmail MCP instances"); // Open Gmail OAuth authorization 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 if (typeof window !== 'undefined') { window.open(gmailMcpInstance.oauthUrl); } ``` ### Step 2: Create Multi-Agent Workflow ```python Python from langgraph.graph import StateGraph, MessagesState from typing import Annotated, Literal from langchain_core.messages import BaseMessage # Get MCP server URLs youtube_mcp_server_url = youtube_mcp_instance.server_url gmail_mcp_server_url = gmail_mcp_instance.server_url # Create a single MCP client with both servers mcp_client = MultiServerMCPClient({ "youtube": { "transport": "streamable_http", "url": youtube_mcp_server_url }, "gmail": { "transport": "streamable_http", "url": gmail_mcp_server_url } }) # Get tools from all MCP servers all_tools = asyncio.run(mcp_client.get_tools()) # Create agents with access to all tools youtube_agent = create_react_agent( model=llm, tools=all_tools, prompt="You are a YouTube video summarization expert. Use MCP tools to analyze and summarize videos. After summarizing, pass the summary to the gmail agent." ) gmail_agent = create_react_agent( model=llm, tools=all_tools, prompt="You are an email assistant. Use MCP tools to send emails via Gmail." ) print("πŸ€– Multi-agent workflow created with YouTube and Gmail agents!") ``` ```typescript TypeScript import { StateGraph, MessagesAnnotation } from "@langchain/langgraph"; // Get MCP server URLs const youtubeMcpServerUrl = youtubeMcpInstance.serverUrl; const gmailMcpServerUrl = gmailMcpInstance.serverUrl; // Create a single MCP client with both servers const mcpClient = new MultiServerMCPClient({ throwOnLoadError: true, useStandardContentBlocks: true, mcpServers: { youtube: { url: youtubeMcpServerUrl, transport: "streamable_http" }, gmail: { url: gmailMcpServerUrl, transport: "streamable_http" } } }); // Get tools from all MCP servers const allTools = await mcpClient.getTools(); // Create agents with access to all tools const youtubeAgent = createReactAgent({ llm: llm, tools: allTools, systemMessage: "You are a YouTube video summarization expert. Use MCP tools to analyze and summarize videos. After summarizing, pass the summary to the gmail agent." }); const gmailAgent = createReactAgent({ llm: llm, tools: allTools, systemMessage: "You are an email assistant. Use MCP tools to send emails via Gmail." }); console.log("πŸ€– Multi-agent workflow created with YouTube and Gmail agents!"); ``` ### Step 3: Create Workflow Graph ```python Python # Define workflow state class WorkflowState(MessagesState): summary: str = "" email_sent: bool = False # Define workflow functions def youtube_summarizer(state: WorkflowState): """Summarize YouTube video""" response = asyncio.run(youtube_agent.ainvoke(state)) return { "messages": response["messages"], "summary": response["messages"][-1].content } def email_sender(state: WorkflowState): """Send email with summary""" email_prompt = f"Send the following summary via email: {state['summary']}" response = asyncio.run(gmail_agent.ainvoke({ "messages": [{"role": "user", "content": email_prompt}] })) return { "messages": response["messages"], "email_sent": True } # Create the workflow graph workflow = StateGraph(WorkflowState) workflow.add_node("youtube_summarizer", youtube_summarizer) workflow.add_node("email_sender", email_sender) # Define the flow workflow.set_entry_point("youtube_summarizer") workflow.add_edge("youtube_summarizer", "email_sender") workflow.set_finish_point("email_sender") # Compile the workflow app = workflow.compile() print("πŸ“Š Multi-agent workflow graph created!") ``` ```typescript TypeScript // Define workflow functions const youtubeSummarizer = async (state: typeof MessagesAnnotation.State) => { const response = await youtubeAgent.invoke(state); return { messages: response.messages, summary: response.messages[response.messages.length - 1].content }; }; const emailSender = async (state: typeof MessagesAnnotation.State & { summary: string }) => { const emailPrompt = `Send the following summary via email: ${state.summary}`; const response = await gmailAgent.invoke({ messages: [{ role: "user", content: emailPrompt }] }); return { messages: response.messages, emailSent: true }; }; // Create the workflow graph const workflow = new StateGraph(MessagesAnnotation) .addNode("youtubeSummarizer", youtubeSummarizer) .addNode("emailSender", emailSender) .setEntryPoint("youtubeSummarizer") .addEdge("youtubeSummarizer", "emailSender") .setFinishPoint("emailSender"); // Compile the workflow const app = workflow.compile(); console.log("πŸ“Š Multi-agent workflow graph created!"); ``` ### Step 4: Run the Multi-Agent Workflow ```python Python YOUTUBE_VIDEO_URL = "https://www.youtube.com/watch?v=LCEmiRjPEtQ" # pick a video you like! EMAIL_RECIPIENT = "example@email.com" # Replace with your email initial_state = { "messages": [{ "role": "user", "content": f"Summarize this video {YOUTUBE_VIDEO_URL} and send it to {EMAIL_RECIPIENT}" }] } # Run the workflow result = asyncio.run(app.ainvoke(initial_state)) print("\nβœ… Workflow Result:", result) ``` ```typescript TypeScript const YOUTUBE_VIDEO_URL = "https://www.youtube.com/watch?v=MmiveeGxfX0"; // pick a video you like! const EMAIL_RECIPIENT = "example@email.com"; // Replace with your email const initialState = { messages: [{ role: "user" as const, content: `Summarize this video ${YOUTUBE_VIDEO_URL} and send it to ${EMAIL_RECIPIENT}` }] }; try { // Run the workflow const result = await app.invoke(initialState); console.log("\nβœ… Workflow Result:", result); } catch (error) { console.error("Error during workflow execution:", error); } finally { // Close MCP client await mcpClient.close(); } ``` ## Next Steps Try other available servers like Slack, Notion, GitHub, etc. Build more complex multi-agent systems with conditional routing Create custom tools and integrate them with your workflows Scale these patterns for production applications with proper error handling ## 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/) * [Klavis AI Documentation](https://docs.klavis.ai/) * [MCP Protocol Specification](https://modelcontextprotocol.io/) * [Klavis MCP Servers](/documentation/mcp-server) **Happy building with LangChain and Klavis!** πŸš€ # LlamaIndex Source: https://docs.klavis.ai/documentation/ai-platform-integration/llamaindex Learn how to build multi-agent workflows using LlamaIndex's agent framework with Klavis MCP Servers ## 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 pip install llama-index llama-index-tools-mcp klavis ``` ```bash TypeScript npm install @llamaindex/tools @llamaindex/workflow @llamaindex/openai klavis ``` ## Setup Environment Variables ```python Python 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 // 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 import os 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 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 }); ``` ## Single Agent Integration Let's start with creating a simple AI agent that can summarize YouTube videos using LlamaIndex and Klavis MCP Server. ### Step 1: Create MCP Server Instance ```python Python # Create a YouTube MCP server and get the server URL youtube_mcp_instance = klavis_client.mcp_server.create_server_instance( server_name=McpServerName.YOUTUBE, user_id="1234", platform_name="Klavis", ) youtube_mcp_server_url = youtube_mcp_instance.server_url print(f"πŸ”— YouTube MCP server created at: {youtube_mcp_server_url}") ``` ```typescript TypeScript // Create a YouTube MCP server and get the server URL const youtubeMcpInstance = await klavisClient.mcpServer.createServerInstance({ serverName: Klavis.McpServerName.Youtube, userId: "1234", platformName: "Klavis", }); const youtubeMcpServerUrl = youtubeMcpInstance.serverUrl; console.log(`πŸ”— YouTube MCP server created at: ${youtubeMcpServerUrl}`); ``` ### Step 2: Create LlamaIndex Agent with MCP Tools ```python Python from llama_index.core.agent.workflow import FunctionAgent # Get tools from MCP server youtube_tools = await aget_tools_from_mcp_url( youtube_mcp_server_url, client=BasicMCPClient(youtube_mcp_server_url) ) # Create agent with MCP-based tools youtube_agent = FunctionAgent( name="youtube_agent", description="Agent using MCP-based tools", tools=youtube_tools, llm=llm, system_prompt="You are an AI assistant that uses MCP tools to analyze YouTube videos." ) print("πŸ€– YouTube AI agent created successfully!") ``` ```typescript TypeScript // Create MCP server connection const youtubeServer = mcp({ url: youtubeMcpServerUrl, verbose: true, }); // Get tools from MCP server const youtubeTools = await youtubeServer.tools(); // Create agent with MCP-based tools const youtubeAgent = agent({ name: "youtube_agent", llm: openai({ model: "gpt-4o" }), tools: youtubeTools, systemPrompt: "You are an AI assistant that uses MCP tools to analyze YouTube videos." }); console.log("πŸ€– YouTube AI agent created successfully!"); ``` ### Step 3: Use the Agent ```python Python YOUTUBE_VIDEO_URL = "https://www.youtube.com/watch?v=MmiveeGxfX0" # pick a video you like! response = await youtube_agent.run(f"Summarize this video: {YOUTUBE_VIDEO_URL}") print("βœ… Video Summary:", response) ``` ```typescript TypeScript const YOUTUBE_VIDEO_URL = "https://www.youtube.com/watch?v=MmiveeGxfX0"; // pick a video you like! const response = await youtubeAgent.run(`Summarize this video: ${YOUTUBE_VIDEO_URL}`); console.log("βœ… Video Summary:", response); ``` ## Multi-Agent Workflow Now let's build a more sophisticated multi-agent workflow that summarizes YouTube videos and sends the summary via email. ### Step 1: Create Multiple MCP Server Instances ```python Python import webbrowser # Create YouTube MCP server youtube_mcp_instance = klavis_client.mcp_server.create_server_instance( server_name=McpServerName.YOUTUBE, user_id="1234", platform_name="Klavis", ) # Create Gmail MCP server with OAuth authorization gmail_mcp_instance = klavis_client.mcp_server.create_server_instance( server_name=McpServerName.GMAIL, user_id="1234", platform_name="Klavis", ) print("βœ… Created YouTube and Gmail MCP instances") # Open Gmail OAuth authorization 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}") ``` ```typescript TypeScript // Create YouTube MCP server const youtubeMcpInstance = await klavisClient.mcpServer.createServerInstance({ serverName: Klavis.McpServerName.Youtube, userId: "1234", platformName: "Klavis", }); // Create Gmail MCP server with OAuth authorization const gmailMcpInstance = await klavisClient.mcpServer.createServerInstance({ serverName: Klavis.McpServerName.Gmail, userId: "1234", platformName: "Klavis", }); console.log("βœ… Created YouTube and Gmail MCP instances"); // Open Gmail OAuth authorization 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); ``` ### Step 2: Create Multi-Agent Workflow ```python Python from llama_index.core.agent.workflow import FunctionAgent, AgentWorkflow # Get MCP server URLs youtube_mcp_server_url = youtube_mcp_instance.server_url gmail_mcp_server_url = gmail_mcp_instance.server_url # Get tools from both MCP servers youtube_tools = await aget_tools_from_mcp_url( youtube_mcp_server_url, client=BasicMCPClient(youtube_mcp_server_url) ) gmail_tools = await aget_tools_from_mcp_url( gmail_mcp_server_url, client=BasicMCPClient(gmail_mcp_server_url) ) # Create specialized agents youtube_agent = FunctionAgent( name="youtube_agent", description="Agent that can summarize YouTube videos", tools=youtube_tools, llm=llm, system_prompt="You are a YouTube video summarization expert. Use MCP tools to analyze and summarize videos.", can_handoff_to=["gmail_agent"], ) gmail_agent = FunctionAgent( name="gmail_agent", description="Agent that can send emails via Gmail", tools=gmail_tools, llm=llm, system_prompt="You are an email assistant. Use MCP tools to send emails via Gmail." ) # Create multi-agent workflow workflow = AgentWorkflow( agents=[youtube_agent, gmail_agent], root_agent="youtube_agent", ) print("πŸ€– Multi-agent workflow created with YouTube and Gmail agents!") ``` ```typescript TypeScript // Get MCP server URLs const youtubeMcpServerUrl = youtubeMcpInstance.serverUrl; const gmailMcpServerUrl = gmailMcpInstance.serverUrl; // Create MCP server connections const youtubeServer = mcp({ url: youtubeMcpServerUrl, verbose: true, }); const gmailServer = mcp({ url: gmailMcpServerUrl, verbose: true, }); // Get tools from both MCP servers const youtubeTools = await youtubeServer.tools(); const gmailTools = await gmailServer.tools(); // Create specialized agents const youtubeAgent = agent({ name: "youtube_agent", llm: openai({ model: "gpt-4o" }), tools: youtubeTools, systemPrompt: "You are a YouTube video summarization expert. Use MCP tools to analyze and summarize videos.", }); const gmailAgent = agent({ name: "gmail_agent", llm: openai({ model: "gpt-4o" }), tools: gmailTools, systemPrompt: "You are an email assistant. Use MCP tools to send emails via Gmail." }); // Create multi-agent workflow const agents = multiAgent({ agents: [youtubeAgent, gmailAgent], rootAgent: youtubeAgent, }); console.log("πŸ€– Multi-agent workflow created with YouTube and Gmail agents!"); ``` ### Step 3: Run the Multi-Agent Workflow ```python Python YOUTUBE_VIDEO_URL = "https://www.youtube.com/watch?v=MmiveeGxfX0" # pick a video you like! EMAIL_RECIPIENT = "example@email.com" # Replace with your email resp = await workflow.run( user_msg=f"Summarize this video {YOUTUBE_VIDEO_URL} and send it to {EMAIL_RECIPIENT}" ) print("\nβœ… Workflow Result:", resp.response.content) ``` ```typescript TypeScript const YOUTUBE_VIDEO_URL = "https://www.youtube.com/watch?v=MmiveeGxfX0"; // pick a video you like! const EMAIL_RECIPIENT = "example@email.com"; // Replace with your email const resp = await agents.run( `Summarize this video ${YOUTUBE_VIDEO_URL} and send it to ${EMAIL_RECIPIENT}` ); console.log("\nβœ… Workflow Result:", resp); ``` ## Next Steps Try other available servers like Slack, Notion, GitHub, etc. Build more complex multi-agent systems with branching logic Create custom tools and integrate them with your workflows Scale these patterns for production applications ## Useful Resources * [LlamaIndex Documentation](https://docs.llamaindex.ai/) * [LlamaIndex Agent Workflows](https://docs.llamaindex.ai/en/stable/understanding/agent/multi_agents/) * [Klavis AI Documentation](https://docs.klavis.ai/) * [MCP Protocol Specification](https://modelcontextprotocol.io/) * [Klavis MCP Servers](/documentation/mcp-server) **Happy building with LlamaIndex and Klavis!** πŸš€ # Mastra Source: https://docs.klavis.ai/documentation/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 # Mastra + Klavis AI Integration This tutorial demonstrates how to use Mastra, an open-source TypeScript framework for building AI agents, with Klavis MCP (Model Context Protocol) servers. ## Prerequisites Before we begin, you'll need: Get your API key from OpenAI Platform Get your API key from Klavis AI ## Getting Started You can find the complete example code in Klavis GitHub repository: **[πŸ“ Checkout the code here](https://github.com/Klavis-AI/klavis/tree/main/examples/mastra)** ## Setup Environment Variables Create a `.env` file in your project root: ```env 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 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 a Gmail MCP Agent with tools from a Klavis-hosted server */ export const createGmailMcpAgent = async (userId: string = 'test-user', platformName: string = 'test-platform'): Promise => { const klavis = new KlavisClient({ apiKey: process.env.KLAVIS_API_KEY! }); // Create a new Gmail MCP server instance const instance = await klavis.mcpServer.createServerInstance({ serverName: Klavis.McpServerName.Gmail, userId, platformName, }); // Redirect user to authorize const response = await klavis.mcpServer.getOAuthUrl({ serverName: Klavis.McpServerName.Gmail, instanceId: instance.instanceId, }); open(response.oauthUrl); // Initialize the MCP client const mcpClient = new MCPClient({ servers: { gmail: { url: new URL(instance.serverUrl), }, }, }); // Get tools from the server const tools = await mcpClient.getTools(); // Create agent return new Agent({ name: 'Gmail MCP Agent', instructions: `You are a Gmail agent with access to Gmail tools: read, send, search emails, and manage labels.`, model: openai('gpt-4o-mini'), tools, }); }; const agent = await createGmailMcpAgent(); export const mastra = new Mastra({ agents: { agent }, }); ``` ## Running the Agent ```bash npm install npm run dev ``` ## Video Tutorial