Integrating LangChain with Amazon Athena Data via CData Connect AI
LangChain is a framework used by developers, data engineers, and AI practitioners for building AI-powered applications and workflows by combining reasoning models (LLMs), tools, APIs, and data connectors. By integrating LangChain with CData Connect AI through the built-in MCP Server, workflows can effortlessly access and interact with live Amazon Athena data in real time.
CData Connect AI offers a secure, low-code environment to connect Amazon Athena and other data sources, removing the need for complex ETL and enabling seamless automation across business applications with live data.
This article outlines how to configure Amazon Athena connectivity in CData Connect AI, register the MCP server with LangChain, and build a workflow that queries Amazon Athena data in real time.
Prerequisites
- An account in CData Connect AI
- Python version 3.10 or higher, to install the LangChain and LangGraph packages
- Generate and save an OpenAI API key
- Install Visual Studio Code in your system
About Amazon Athena Data Integration
CData provides the easiest way to access and integrate live data from Amazon Athena. Customers use CData connectivity to:
- Authenticate securely using a variety of methods, including IAM credentials, access keys, and Instance Profiles, catering to diverse security needs and simplifying the authentication process.
- Streamline their setup and quickly resolve issue with detailed error messaging.
- Enhance performance and minimize strain on client resources with server-side query execution.
Users frequently integrate Athena with analytics tools like Tableau, Power BI, and Excel for in-depth analytics from their preferred tools.
To learn more about unique Amazon Athena use cases with CData, check out our blog post: https://www.cdata.com/blog/amazon-athena-use-cases.
Getting Started
Step 1: Configure Amazon Athena Connectivity for LangChain
Before LangChain can access Amazon Athena, a Amazon Athena connection must be created in CData Connect AI. This connection is then exposed to LangChain through the remote MCP server.
- Log in to Connect AI click Sources, and then click + Add Connection
- From the available data sources, choose Amazon Athena
-
Enter the necessary authentication properties to connect to Amazon Athena
Authenticating to Amazon Athena
To authorize Amazon Athena requests, provide the credentials for an administrator account or for an IAM user with custom permissions: Set AccessKey to the access key Id. Set SecretKey to the secret access key.
Note: Though you can connect as the AWS account administrator, it is recommended to use IAM user credentials to access AWS services.
Obtaining the Access Key
To obtain the credentials for an IAM user, follow the steps below:
- Sign into the IAM console.
- In the navigation pane, select Users.
- To create or manage the access keys for a user, select the user and then select the Security Credentials tab.
To obtain the credentials for your AWS root account, follow the steps below:
- Sign into the AWS Management console with the credentials for your root account.
- Select your account name or number and select My Security Credentials in the menu that is displayed.
- Click Continue to Security Credentials and expand the Access Keys section to manage or create root account access keys.
Authenticating from an EC2 Instance
If you are using the CData Data Provider for Amazon Athena 2018 from an EC2 Instance and have an IAM Role assigned to the instance, you can use the IAM Role to authenticate. To do so, set UseEC2Roles to true and leave AccessKey and SecretKey empty. The CData Data Provider for Amazon Athena 2018 will automatically obtain your IAM Role credentials and authenticate with them.
Authenticating as an AWS Role
In many situations it may be preferable to use an IAM role for authentication instead of the direct security credentials of an AWS root user. An AWS role may be used instead by specifying the RoleARN. This will cause the CData Data Provider for Amazon Athena 2018 to attempt to retrieve credentials for the specified role. If you are connecting to AWS (instead of already being connected such as on an EC2 instance), you must additionally specify the AccessKey and SecretKey of an IAM user to assume the role for. Roles may not be used when specifying the AccessKey and SecretKey of an AWS root user.
Authenticating with MFA
For users and roles that require Multi-factor Authentication, specify the MFASerialNumber and MFAToken connection properties. This will cause the CData Data Provider for Amazon Athena 2018 to submit the MFA credentials in a request to retrieve temporary authentication credentials. Note that the duration of the temporary credentials may be controlled via the TemporaryTokenDuration (default 3600 seconds).
Connecting to Amazon Athena
In addition to the AccessKey and SecretKey properties, specify Database, S3StagingDirectory and Region. Set Region to the region where your Amazon Athena data is hosted. Set S3StagingDirectory to a folder in S3 where you would like to store the results of queries.
If Database is not set in the connection, the data provider connects to the default database set in Amazon Athena.
- Click Save & Test
- Once authenticated, open the Permissions tab in the Amazon Athena connection and configure user-based permissions as required
Generate a Personal Access Token (PAT)
LangChain authenticates to Connect AI using an account email and a Personal Access Token (PAT). Creating separate PATs for each integration is recommended to maintain access control granularity.
- In Connect AI, select the Gear icon in the top-right to open Settings
- Under Access Tokens, select Create PAT
- Provide a descriptive name for the token and select Create
- Copy the token and store it securely. The PAT will only be visible during creation
With the Amazon Athena connection configured and a PAT generated, LangChain is prepared to connect to Amazon Athena data through the CData MCP server.
Note: You can also generate a PAT from LangChain in the Integrations section of Connect AI. Simply click Connect --> Create PAT to generate it.
Step 2: Connect to the MCP server in LangChain
To connect LangChain with CData Connect AI Remote MCP Server and use OpenAI (ChatGPT) for reasoning, you need to configure your MCP server endpoint and authentication values in a config.py file. These values allow LangChain to call the MCP server tools, while OpenAI handles the natural language reasoning.
- Create a folder for LangChain MCP
- Create two Python files within the folder: config.py and langchain.py
- In config.py, create a class Config to define your MCP server authentication and URL. You need to provide your Base64-encoded CData Connect AI username and PAT (obtained in the prerequisites):
class Config: MCP_BASE_URL = "https://mcp.cloud.cdata.com/mcp" #MCP Server URL MCP_AUTH = "base64encoded(EMAIL:PAT)" #Base64 encoded Connect AI Email:PATNote: You can create the base64 encoded version of MCP_AUTH using any Base64 encoding tool.
- In langchain.py, set up your MCP server and MCP client to call the tools and prompts:
""" Integrates a LangChain ReAct agent with CData Connect AI MCP server. The script demonstrates fetching, filtering, and using tools with an LLM for agent-based reasoning. """ import asyncio from langchain_mcp_adapters.client import MultiServerMCPClient from langchain_openai import ChatOpenAI from langgraph.prebuilt import create_react_agent from config import Config async def main(): # Initialize MCP client with one or more server URLs mcp_client = MultiServerMCPClient( connections={ "default": { # you can name this anything "transport": "streamable_http", "url": Config.MCP_BASE_URL, "headers": {"Authorization": f"Basic {Config.MCP_AUTH}"}, } } ) # Load remote MCP tools exposed by the server all_mcp_tools = await mcp_client.get_tools() print("Discovered MCP tools:", [tool.name for tool in all_mcp_tools]) # Create and run the ReAct style agent llm = ChatOpenAI( model="gpt-4o", temperature=0.2, api_key="YOUR_OPEN_API_KEY" #Use your OpenAI API Key here, this can be found here: https://platform.openai.com/ ) agent = create_react_agent(llm, all_mcp_tools) user_prompt = "How many tables are available in AmazonAthena1?" #Change prompts as per need print(f" User prompt: {user_prompt}") # Send a prompt asking the agent to use the MCP tools response = await agent.ainvoke( { "messages": [{ "role": "user", "content": (user_prompt),}]} ) # Print out the agent's final response final_msg = response["messages"][-1].content print("Agent final response:", final_msg) if __name__ == "__main__": asyncio.run(main())
Step 3: Install the LangChain and LangGraph packages
Since this workflow uses LangChain together with CData Connect AI MCP and integrates OpenAI for reasoning, you need to install the required Python packages.
Run the following command in your project terminal:
pip install langchain-mcp-adapters langchain-openai langgraph
Step 4: Prompt Amazon Athena using LangChain (via the MCP server)
- When the installation finishes, run python langchain.py to execute the script
- The script connects to the MCP server and discovers the CData Connect AI MCP tools available for querying your connected data
- Supply a prompt (e.g., "How many tables are available in Amazon Athena?")
- Accordingly, the agent responds with the results
Get CData Connect AI
To get live data access to 300+ SaaS, Big Data, and NoSQL sources directly from your cloud applications, try CData Connect AI today!