Skip to content

CDataSoftware/connectai-claude-agent

Repository files navigation

CData Connect AI Agent Chatbot

A production-ready chatbot built with the Claude Agent SDK that connects to the CData Connect AI MCP Server. Demonstrates how to build AI agents with stateful conversations, automatic context management, and native MCP tool integration.

Features

  • 🧠 Stateful Conversations: Automatic context management across multiple turns
  • 🛠️ Built-in Tool Framework: Native MCP tool integration with proper lifecycle management
  • 🎯 Production-Ready: Built on the same agent harness that powers Claude Code
  • Context Management: Automatic context compaction to prevent running out of context
  • 🎛️ Advanced Controls: Fine-grained permissions, hooks, and behavioral customization
  • 🔌 Connects to CData Connect AI MCP Server at https://mcp.cloud.cdata.com/mcp/
  • 🔐 Basic authentication with email and personal access token
  • 🤖 Uses Claude Sonnet 4.5 via Agent SDK
  • 💬 Dynamic MCP tool loading and integration
  • 🖥️ Interactive command-line interface
  • ⚡ Async/await architecture for better performance

Interested in embedding connectivity into your product?

Learn more about Embedded Cloud for AI:

Prerequisites

Setup

  1. Install dependencies:
pip install -r requirements.txt
  1. Set up environment variables:
cp .env.example .env
# Edit .env and add your credentials
  1. Run the chatbot:
python3 agent_chatbot.py

Configuration

Required Environment Variables

  • ANTHROPIC_API_KEY: Your Anthropic API key
  • CDATA_EMAIL: Your CData account email
  • CDATA_ACCESS_TOKEN: Your CData personal access token

Get Your CData Connect AI Credentials

  1. Sign up at CData Connect AI
  2. Add a data source connection (e.g., Google Sheets, Salesforce, HubSpot)
  3. Navigate to Settings > Access Tokens > Create PAT
  4. Copy the token immediately (it's only shown once!)
  5. Use your account email for CDATA_EMAIL and the PAT for CDATA_ACCESS_TOKEN

Setting up credentials

export ANTHROPIC_API_KEY="your_api_key"
export CDATA_EMAIL="your_email@example.com"
export CDATA_ACCESS_TOKEN="your_personal_access_token"

Or create a .env file:

cp .env.example .env
# Edit .env with your credentials

Usage

Interactive Mode (Stateful Sessions)

python3 agent_chatbot.py

The chatbot creates a stateful session using ClaudeSDKClient, which:

  • Maintains conversation context automatically
  • Tracks tool usage across turns
  • Manages memory and context compaction

Programmatic Usage

One-off Queries

from agent_chatbot import MCPAgentChatbot
import asyncio

async def main():
    chatbot = MCPAgentChatbot(
        mcp_server_url="https://mcp.cloud.cdata.com/mcp/",
        email="your_email@example.com",
        access_token="your_personal_access_token"
    )

    # Single query (creates new session)
    response = await chatbot.chat_once("What data sources are available?")
    print(response)

asyncio.run(main())

Stateful Conversations

from agent_chatbot import MCPAgentChatbot
import asyncio

async def main():
    chatbot = MCPAgentChatbot(
        mcp_server_url="https://mcp.cloud.cdata.com/mcp/",
        email="your_email@example.com",
        access_token="your_personal_access_token"
    )

    # Create stateful session
    client = chatbot.create_session()

    # Multiple turns with context
    async with client:
        response1 = await chatbot.chat_session(client, "List my data sources")
        response2 = await chatbot.chat_session(client, "Tell me more about the first one")

asyncio.run(main())

How It Works

Agent SDK Architecture

  1. MCP Tool Discovery: Fetches available tools from CData Connect AI
  2. Tool Wrapping: Converts MCP tools to Agent SDK format using @tool decorator
  3. MCP Server Creation: Creates SDK-compatible MCP server with create_sdk_mcp_server()
  4. Agent Configuration: Sets up ClaudeAgentOptions with tools and permissions
  5. Stateful Sessions: Uses ClaudeSDKClient for continuous conversations
  6. Automatic Tool Calling: Agent SDK handles tool execution lifecycle automatically

Key Components

1. Tool Wrapping

@tool(
    name="data_source_query",
    description="Query a data source",
    input_schema={"type": "object", ...}
)
async def tool_handler(args):
    result = mcp_client.call_tool("data_source_query", args)
    return {"content": [{"type": "text", "text": json.dumps(result)}]}

2. MCP Server Integration

mcp_server = create_sdk_mcp_server(
    name="cdata_connect",
    tools=[tool1, tool2, ...]
)

3. Agent Configuration

options = ClaudeAgentOptions(
    system_prompt="You are a helpful assistant...",
    mcp_servers={"cdata_connect": mcp_server},  # Dictionary of MCP servers
    permission_mode="bypassPermissions"  # Options: "default", "acceptEdits", "bypassPermissions", "plan"
)

4. Stateful Client

client = ClaudeSDKClient(options=options)

# Maintains context automatically using async context manager
async with client:
    await client.query("First question")
    async for msg in client.receive_response():
        print(msg)

    await client.query("Follow-up question")
    async for msg in client.receive_response():
        print(msg)

Key Benefits

1. Automatic Context Management

  • No manual conversation history tracking
  • Automatic context compaction when approaching limits
  • Built-in memory management

2. Native Tool Integration

  • Tools are first-class citizens
  • Automatic tool calling lifecycle
  • Better error handling and retries

3. Production-Ready Patterns

  • Session management
  • Permission controls
  • Hook system for customization

4. Better Developer Experience

  • Async/await throughout
  • Streaming support
  • Cleaner abstractions

Troubleshooting

Authentication Errors (401)

  • Verify your CData email is correct
  • Ensure your personal access token is valid and not expired
  • Check that you have access to the CData Connect AI service

Tool Loading Issues

  • Verify connection to https://mcp.cloud.cdata.com/mcp/
  • Check network connectivity and firewall settings
  • Ensure MCP server is responding to tools/list requests

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

Project Structure

connect-ai-claude-agent/
├── agent_chatbot.py          # Standalone chatbot script
├── src/
│   └── connectai_claude/     # Library package
│       ├── __init__.py
│       ├── config.py         # Configuration management
│       ├── mcp_client.py     # MCP server communication
│       └── agent.py          # Agent SDK integration
├── examples/
│   ├── basic_chat.py         # Interactive chat example
│   ├── one_off_query.py      # Single query example
│   ├── data_exploration.py   # Direct MCP client usage
│   └── programmatic_usage.py # Multi-turn conversation example
├── docs/
│   └── API.md                # API documentation
├── tests/                    # Unit tests
├── requirements.txt          # Dependencies
├── pyproject.toml            # Modern Python packaging
├── .env.example              # Example environment file
└── LICENSE                   # MIT License

Available MCP Tools

Your 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
getInstructions Get driver-specific instructions and best practices for a data source

SQL Query Format

When executing queries, use fully qualified table names:

SELECT [column1], [column2]
FROM [CatalogName].[SchemaName].[TableName]
WHERE [column1] = 'value'
ORDER BY [column2]
LIMIT 100

Learn More

License

MIT License - see LICENSE for details.

About

A production-ready chatbot built with the **Claude Agent SDK** that connects to the **CData Connect AI MCP Server**. Demonstrates how to build AI agents with stateful conversations, automatic context management, and native MCP tool integration.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages