Developer Guide - Build Production-Ready AI Agents with Claude Agent SDK
Build production-ready AI agents with stateful conversations, automatic context management, and native MCP tool integration. This guide walks you through creating a Python application using the Claude Agent SDK with CData Connect AI to enable conversational access to your data.
NOTE: While this guide uses Google Sheets as the data source, the same principles apply to any of the 350+ data sources CData Connect AI supports.
By the end of this guide, you'll have a working Python application that can:
- Connect to any of 350+ data sources through CData Connect AI
- Maintain stateful conversations with automatic context management
- Execute SQL queries using natural language
- Handle multi-turn conversations with context preserved across turns
- Use production-ready patterns from the same framework that powers Claude Code
Why Claude Agent SDK?
The Claude Agent SDK provides several key advantages for building AI agents:
- Automatic Context Management: No manual conversation history tracking - the SDK handles it automatically
- Stateful Conversations: Maintain context across multiple turns for natural, flowing interactions
- Native Tool Integration: Tools are first-class citizens with automatic calling lifecycle and error handling
- Context Compaction: Automatic context compaction when approaching token limits
- Production-Ready: Built on the same agent harness that powers Claude Code
- Async/Await Architecture: Modern Python async patterns for better performance
Architecture Overview
The application uses the Model Context Protocol (MCP) to bridge Claude with your data sources:
┌─────────────────┐ ┌──────────────────┐ ┌─────────────────┐
│ │ │ │ │ │
│ Your Python │---->│ CData Connect │---->│ Data Sources │
│ Application │ │ AI MCP Server │ │ (300+ types) │
│ │<----│ │<----│ │
└─────────────────┘ └──────────────────┘ └─────────────────┘
| |
| Tool Discovery |
| & Execution |
v |
┌─────────────────┐ |
│ │ |
│ Claude API │--------------┘
│ (Agent SDK) │ Natural Language
│ │ to SQL Translation
└─────────────────┘
How it works:
- Your Python application connects to CData Connect AI's MCP server over HTTP
- MCP tools are discovered and wrapped for the Claude Agent SDK
- The Agent SDK manages stateful conversations and tool execution
- Claude translates natural language into SQL queries
- Results are returned and interpreted by the AI
Prerequisites
This guide requires the following:
- Python 3.8+ installed on your system
- An Anthropic API key
- A CData Connect AI account (free trial available)
- A Google account for the sample Google Sheets data
Getting Started
Overview
Here's a quick overview of the steps:
- Set up sample data in Google Sheets
- Configure CData Connect AI and create a Personal Access Token
- Set up the Python project and install dependencies
- Build and run the agent chatbot
STEP 1: Set Up Sample Data in Google Sheets
We'll use a sample Google Sheet containing customer data to demonstrate the capabilities. This dataset includes accounts, sales opportunities, support tickets, and usage metrics.
- Navigate to the sample customer health spreadsheet
- Click File > Make a copy to save it to your Google Drive
- Give it a memorable name (e.g., "demo_organization") - you'll need this later
The spreadsheet contains four sheets:
- account: Company information (name, industry, revenue, employees)
- opportunity: Sales pipeline data (stage, amount, probability)
- tickets: Support tickets (priority, status, description)
- usage: Product usage metrics (job runs, records processed)
STEP 2: Configure CData Connect AI
2.1 Sign Up or Log In
- Navigate to https://www.cdata.com/ai/signup/ to create a new account, or https://cloud.cdata.com/ to log in
- Complete the registration process if creating a new account
2.2 Add a Google Sheets Connection
-
Once logged in, click Sources in the left navigation menu and click Add Connection
-
Select Google Sheets from the Add Connection panel
-
Configure the connection:
- Set the Spreadsheet property to the name of your copied sheet (e.g., "demo_organization")
- Click Sign in to authenticate with Google OAuth
-
After authentication, navigate to the Permissions tab and verify your user has access
2.3 Create a Personal Access Token
Your Python application will use a Personal Access Token (PAT) to authenticate with Connect AI.
- Click the Gear icon in the top right to open Settings
- Go to the Access Tokens section
- Click Create PAT
-
Give the token a name (e.g., "Claude Agent SDK App") and click Create
- Important: Copy the token immediately - it's only shown once!
STEP 3: Set Up the Python Project
3.1 Clone from GitHub (Recommended)
Clone the complete project with all examples:
git clone https://github.com/CDataSoftware/connectai-claude-agent.git
cd connectai-claude-agent
pip install -r requirements.txt
3.2 Alternative: Create from Scratch
Create a new project directory and install dependencies:
mkdir connectai-claude-agent
cd connectai-claude-agent
pip install claude-agent-sdk python-dotenv requests
3.3 Configure Environment Variables
Create a .env file in your project root:
# Anthropic Configuration
ANTHROPIC_API_KEY=your_anthropic_api_key
# CData Connect AI Configuration
[email protected]
CDATA_ACCESS_TOKEN=your_personal_access_token
Replace the placeholder values with your actual credentials.
STEP 4: Understanding the Code Architecture
The project consists of three main components:
4.1 MCPClient Class
Handles HTTP communication with the CData Connect AI MCP server. It manages authentication using Basic Auth and parses Server-Sent Events (SSE) responses:
import json
import base64
import sys
import requests
class MCPClient:
"""Client for interacting with CData Connect AI MCP server over HTTP."""
def __init__(self, server_url: str, email: str = None, access_token: str = None):
self.server_url = server_url.rstrip('/')
self.session = requests.Session()
# Set default headers for MCP JSON-RPC
self.session.headers.update({
'Content-Type': 'application/json',
'Accept': 'application/json, text/event-stream',
'User-Agent': f'CDataConnectAI-ClaudeAgent (Python/{sys.version_info.major}.{sys.version_info.minor})',
})
if email and access_token:
# Basic authentication: email:personal_access_token
credentials = f"{email}:{access_token}"
encoded_credentials = base64.b64encode(credentials.encode()).decode()
self.session.headers.update({
'Authorization': f'Basic {encoded_credentials}'
})
def _parse_sse_response(self, response_text: str) -> dict:
"""Parse Server-Sent Events (SSE) response."""
for line in response_text.split('
'):
if line.startswith('data: '):
return json.loads(line[6:])
raise ValueError("No data found in SSE response")
def list_tools(self) -> list:
"""Get available tools from the MCP server."""
response = self.session.post(
self.server_url,
json={"jsonrpc": "2.0", "method": "tools/list", "params": {}, "id": 1}
)
response.raise_for_status()
result = self._parse_sse_response(response.text)
return result.get("result", {}).get("tools", [])
def call_tool(self, tool_name: str, arguments: dict) -> dict:
"""Call a tool on the MCP server."""
response = self.session.post(
self.server_url,
json={
"jsonrpc": "2.0",
"method": "tools/call",
"params": {"name": tool_name, "arguments": arguments},
"id": 2
}
)
response.raise_for_status()
result = self._parse_sse_response(response.text)
return result.get("result", {})
4.2 MCPAgentChatbot Class
The core of the application - connects the MCP client to the Claude Agent SDK with stateful conversations and automatic context management:
from typing import Optional, Dict, Any
from functools import partial
from claude_agent_sdk import query, ClaudeSDKClient, ClaudeAgentOptions, tool, create_sdk_mcp_server
class MCPAgentChatbot:
"""Production-ready AI agent chatbot for CData Connect AI."""
def __init__(self, mcp_server_url: str, email: str = None, access_token: str = None):
self.mcp_client = MCPClient(mcp_server_url, email, access_token)
# Load available tools from MCP server
print("Connecting to CData Connect AI MCP server...")
self.mcp_tools_list = self.mcp_client.list_tools()
print(f"Loaded {len(self.mcp_tools_list)} tools from MCP server")
# Create Agent SDK tool wrappers
self.agent_tools = self._create_agent_tools()
# Create MCP server for Agent SDK
self.mcp_server = create_sdk_mcp_server(
name="cdata_connect",
tools=self.agent_tools
)
async def _tool_handler(self, tool_name: str, args: Dict[str, Any]) -> Dict[str, Any]:
"""Call the MCP tool and return results."""
result = self.mcp_client.call_tool(tool_name, args)
return {
"content": [{
"type": "text",
"text": json.dumps(result, indent=2)
}]
}
def _create_agent_tools(self) -> list:
"""Create Agent SDK tool wrappers for MCP tools."""
agent_tools = []
for tool_info in self.mcp_tools_list:
tool_name = tool_info.get("name")
tool_description = tool_info.get("description", "")
tool_schema = tool_info.get("inputSchema", {})
agent_tool = tool(
name=tool_name,
description=tool_description,
input_schema=tool_schema
)(partial(self._tool_handler, tool_name))
agent_tools.append(agent_tool)
return agent_tools
4.3 Stateful Session Management
The Agent SDK provides stateful conversation sessions with automatic context management:
def create_session(self) -> ClaudeSDKClient:
"""Create a stateful conversation session."""
options = ClaudeAgentOptions(
system_prompt="You are a helpful assistant with access to CData Connect AI data sources.",
mcp_servers={"cdata_connect": self.mcp_server},
permission_mode="bypassPermissions"
)
return ClaudeSDKClient(options=options)
async def chat_session(self, client: ClaudeSDKClient, user_message: str) -> str:
"""Send a message in a stateful session."""
await client.query(user_message)
async for message in client.receive_response():
if hasattr(message, 'result'):
return str(message.result)
return ""
STEP 5: Build the Agent Chatbot
Create an interactive agent chatbot with stateful sessions:
#!/usr/bin/env python3
"""Interactive agent chatbot for querying data with AI."""
import os
import asyncio
from dotenv import load_dotenv
load_dotenv()
async def interactive_mode(chatbot):
"""Run the chatbot in interactive mode with stateful sessions."""
print("
Chatbot ready! Type 'quit' to exit.
")
# Create a stateful session
client = chatbot.create_session()
# Use async context manager for proper resource cleanup
async with client:
while True:
user_input = input("You: ").strip()
if not user_input:
continue
if user_input.lower() in ['quit', 'exit', 'q']:
print("Goodbye!")
break
response = await chatbot.chat_session(client, user_input)
print(f"
Assistant: {response}
")
async def main():
"""Run the chatbot in interactive mode."""
MCP_SERVER_URL = "https://mcp.cloud.cdata.com/mcp/"
CDATA_EMAIL = os.environ.get("CDATA_EMAIL")
CDATA_ACCESS_TOKEN = os.environ.get("CDATA_ACCESS_TOKEN")
print("=== CData Connect AI Agent Chatbot ===")
print(f"MCP Server: {MCP_SERVER_URL}
")
chatbot = MCPAgentChatbot(MCP_SERVER_URL, CDATA_EMAIL, CDATA_ACCESS_TOKEN)
await interactive_mode(chatbot)
if __name__ == "__main__":
asyncio.run(main())
STEP 6: Run Your Application
With everything configured, run your agent chatbot:
python agent_chatbot.py
You should see output like:
=== CData Connect AI Agent Chatbot ===
MCP Server: https://mcp.cloud.cdata.com/mcp/
Connecting to CData Connect AI MCP server...
Loaded 8 tools from MCP server
Available tools:
- getCatalogs
- getSchemas
- getTables
- getColumns
- queryData
... and 3 more
Chatbot ready! Type 'quit' to exit.
You: What data sources do I have?
STEP 7: Example Queries
Here are some example prompts to try with your agent chatbot:
Data Discovery
- "What data sources do I have connected?"
- "Show me all the tables in demo_organization"
- "What columns are in the account table?"
Basic Queries
- "Query the top 5 accounts by annual_revenue"
- "How many support tickets are there by priority?"
- "Show me all open opportunities"
Multi-Turn Conversations
The Agent SDK maintains context across turns, enabling natural follow-up questions:
- You: "Show me the accounts table"
- You: "Which one has the highest revenue?"
- You: "Tell me more about that company"
STEP 8: Available MCP Tools
Your AI agent has access to these CData Connect AI tools:
| Tool | Description |
|---|---|
| getCatalogs | List available data source connections |
| getSchemas | Get schemas for a specific catalog |
| getTables | Get tables in a schema |
| getColumns | Get column metadata for a table |
| queryData | Execute SQL queries |
| getProcedures | List stored procedures |
| getProcedureParameters | Get procedure parameter details |
| executeProcedure | Execute stored procedures |
STEP 9: Permission Modes
The Claude Agent SDK offers different permission modes for tool execution:
| Mode | Description |
|---|---|
| default | Prompts user for approval before executing tools |
| acceptEdits | Automatically accepts edit operations |
| bypassPermissions | Auto-approves all tools (recommended for CLI applications) |
| plan | Agent plans actions before execution |
Troubleshooting
Authentication Errors
- Verify your CData email and access token are correct in .env
- Ensure the access token has not expired
- Check that your Connect AI account is active
No Tools Available
- Confirm you have at least one data source connected in Connect AI
- Check that your user has permissions to access the connection
Agent SDK Errors
- Make sure claude-agent-sdk is installed:
pip install claude-agent-sdk - Check that you're using Python 3.8+
- Verify your ANTHROPIC_API_KEY is set correctly
What's Next?
Now that you have a working AI agent, you can:
- Connect more data sources: Add Salesforce, Snowflake, or any of 350+ supported sources to expand your data access.
- Customize the agent: Modify the system prompt for your specific use case and domain.
- Build production applications: Integrate the agent into web apps, Slack bots, or other interfaces.
- Explore advanced features: Use hooks for customization, streaming for real-time responses, and context compaction for long conversations.
Resources
- GitHub Repository - Complete source code and examples
- CData Connect AI Documentation
- CData Prompt Library - Example prompts for various use cases
- Claude Agent SDK Documentation
- Model Context Protocol
Get Started with CData Connect AI
Ready to build production-ready AI agents? CData Connect AI provides live data access to 350+ SaaS, Big Data, and NoSQL sources directly from your AI applications.
Sign up for a free trial and start building intelligent data assistants today!