Prerequisites

Before we begin, you’ll need:

Installation

First, install the required packages:

pip install anthropic klavis

Setup Environment Variables

import os

# Set environment variables
os.environ["ANTHROPIC_API_KEY"] = "your-anthropic-api-key-here"  # Replace with your actual Anthropic API key
os.environ["KLAVIS_API_KEY"] = "your-klavis-api-key-here"       # Replace with your actual Klavis API key

Basic Setup

import os
import json
from anthropic import Anthropic
from klavis import Klavis
from klavis.types import McpServerName, ConnectionType, ToolFormat

# Initialize clients
anthropic_client = Anthropic(api_key=os.getenv("ANTHROPIC_API_KEY"))
klavis_client = Klavis(api_key=os.getenv("KLAVIS_API_KEY"))

# Constants
CLAUDE_MODEL = "claude-3-5-sonnet-20241022"  # or "claude-3-opus-20240229", "claude-3-haiku-20240307"

AI Agent with MCP Integration

Now we’ll create an intelligent agent that can use MCP servers through Klavis API. This agent will:

  1. Create MCP Instances: Set up connections to external services
  2. Tool Discovery: Automatically find available tools from MCP servers
  3. Function Calling: Use Claude’s advanced tool use capabilities
  4. Tool Execution: Execute tools through Klavis API
  5. Smart Responses: Generate intelligent responses based on tool results
def claude_with_mcp_server(mcp_server_url: str, user_query: str):
    """Process a user request using Claude + Klavis integration."""
    
    messages = [
        {"role": "user", "content": f"{user_query}"}
    ]
    
    # 1. Get available tools from MCP server
    mcp_server_tools = klavis_client.mcp_server.list_tools(
        server_url=mcp_server_url,
        connection_type=ConnectionType.STREAMABLE_HTTP,
        format=ToolFormat.ANTHROPIC,
    )
    
    # 2. First Claude call with tool use
    response = anthropic_client.messages.create(
        model=CLAUDE_MODEL,
        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})

    # 3. Handle tool calls if requested
    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}")
                
                # Call tool via Klavis API
                result = klavis_client.mcp_server.call_tools(
                    server_url=mcp_server_url,
                    tool_name=function_name,
                    tool_args=function_args,
                    connection_type=ConnectionType.STREAMABLE_HTTP
                )
                
                tool_results.append({
                    "type": "tool_result",
                    "tool_use_id": content_block.id,
                    "content": str(result)
                })
        
        messages.append({"role": "user", "content": tool_results})
            
        # 4. Second Claude call to process tool results
        final_response = anthropic_client.messages.create(
            model=CLAUDE_MODEL,
            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

Use Case Examples

Example 1: YouTube Video Summarization

1

Create YouTube Server

Set up a YouTube MCP server instance

2

Analyze Video

Use Claude to summarize a YouTube video with timestamps

# Create YouTube MCP server using Klavis
youtube_mcp_instance = klavis_client.mcp_server.create_server_instance(
    server_name=McpServerName.YOUTUBE,
    user_id="1234",
    platform_name="Klavis",
    connection_type=ConnectionType.STREAMABLE_HTTP,
)

# Summarize your favorite video
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"Please provide a complete summary of this YouTube video with timestamp: {YOUTUBE_VIDEO_URL}"
)

print(result)

Example 2: Gmail Email Management

Gmail integration requires OAuth authentication, so you’ll need to authorize the application in your browser.

1

Create Gmail Server

Create a Gmail MCP server instance

2

OAuth Authorization

Complete OAuth flow for Gmail access

3

Send Email

Use Claude to send an email

import webbrowser

# Create Gmail MCP server
gmail_mcp_server = klavis_client.mcp_server.create_server_instance(
    server_name=McpServerName.GMAIL,
    user_id="1234",
    platform_name="Klavis",
    connection_type=ConnectionType.STREAMABLE_HTTP,
)

# Open OAuth 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}")

# After OAuth authorization, send an email
EMAIL_RECIPIENT = "example@email.com"  # 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)

Complete Integration Example

Here’s a complete working example that demonstrates the full integration:

import os
import json
import webbrowser
from anthropic import Anthropic
from klavis import Klavis
from klavis.types import McpServerName, ConnectionType, ToolFormat

# Setup
os.environ["ANTHROPIC_API_KEY"] = "your-anthropic-api-key-here"
os.environ["KLAVIS_API_KEY"] = "your-klavis-api-key-here"

anthropic_client = Anthropic(api_key=os.getenv("ANTHROPIC_API_KEY"))
klavis_client = Klavis(api_key=os.getenv("KLAVIS_API_KEY"))

def claude_with_mcp_server(mcp_server_url: str, user_query: str):
    messages = [{"role": "user", "content": f"{user_query}"}]
    
    mcp_server_tools = klavis_client.mcp_server.list_tools(
        server_url=mcp_server_url,
        connection_type=ConnectionType.STREAMABLE_HTTP,
        format=ToolFormat.ANTHROPIC,
    )
    
    response = anthropic_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,
                    connection_type=ConnectionType.STREAMABLE_HTTP
                )
                
                tool_results.append({
                    "type": "tool_result",
                    "tool_use_id": content_block.id,
                    "content": str(result)
                })
        
        messages.append({"role": "user", "content": tool_results})
            
        final_response = anthropic_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

# Create YouTube MCP instance
youtube_mcp_instance = klavis_client.mcp_server.create_server_instance(
    server_name=McpServerName.YOUTUBE,
    user_id="1234",
    platform_name="Klavis",
    connection_type=ConnectionType.STREAMABLE_HTTP,
)

# Use the integration
YOUTUBE_VIDEO_URL = "https://www.youtube.com/watch?v=LCEmiRjPEtQ"
result = claude_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("✅ Summary:", result)

Next Steps

Explore More MCP Servers

Try other available servers like Slack, Notion, GitHub, etc.

Advanced Workflows

Build multi-step workflows combining multiple MCP servers

Production Deployment

Scale these patterns for production applications

Custom Integrations

Build custom MCP servers for your specific needs

Useful Resources

Happy building with Claude and Klavis! 🚀