
How can DuckDB help Strands agent to work with ephemeral structured data
If you have some data set (say few MBs or tens of MBs) which is quite structured and can be presented as CSV, what's the most efficient way to allow your Agent working with this data and exploring it? Feeding it completely to LLM is not feasible. Saving it to the DB for just few interactions and then cleaning it up? Too much of a hassle.
Problem definition
Let's assume you have an agent which has access to different tools. One of the tools is doing an API call which returns megabytes of structured data. How to make sense of that data without flooding your context window? How to get the answer to your question quicker, spending reasonable amount of tokens for this? At the same time, if you want to run analytical type of questions, probably LLM is not the best tool for that.

Solution
There are multiple ways to do it and one of them is text-to-SQL with in-memory DB. And this is what I will describe below. With in-memory DB, instead of loading data completely to context window, agent would fetch only the data which is relevant for answering the question at hand. And if data should be aggregated and searched in some way, then it's better to give these tasks to dedicated tool.
Let's get more concrete now, let's say we have fetched stock prices data from 3rd party API and we have stored it on S3. We don't want to save this data to the DB or keep in our data lake permanently, let's say that it's valid only for one request.
We want now to build Strands agent and make it use in-memory DB to access data on S3. We can use MotherDuck MCP server for that. In this example I'll run an agent in ECS. The agent will receive queries from users and will use data on S3 to answer the questions. Please note that I use file already stored on S3 for simplicity. In practice, same agent could have downloaded the data, saved it locally and they used MotherDuck MCP to query it.

In this example ECS task runs Flask server with a route mapped to /query and it expects to get user question as a query parameter as well as location of the data on S3. Remember this is for demonstration only. And as your ECS task accesses data on S3, its task role should have enough permissions to read the data.
from strands.tools.mcp import MCPClient from mcp import stdio_client, StdioServerParametersfrom strands import Agentfrom flask import Flask, request, jsonifyimport boto3import os
def get_aws_credentials(): """Get AWS credentials from the ECS task role""" session = boto3.Session() credentials = session.get_credentials() return { "AWS_ACCESS_KEY_ID": credentials.access_key, "AWS_SECRET_ACCESS_KEY": credentials.secret_key, "AWS_SESSION_TOKEN": credentials.token, "AWS_DEFAULT_REGION": session.region_name } @app.route('/query', methods=['POST']) def query(): # Get request parameters request_data = request.get_json() user_query = request_data.get('query', '') s3_bucket = request_data.get('s3_bucket', os.environ.get('S3_BUCKET')) s3_key = request_data.get('s3_key', os.environ.get('S3_KEY')) model = request_data.get('model', 'eu.anthropic.claude-sonnet-4-20250514-v1:0') file_name = f's3://{s3_bucket}/{s3_key}' ...Then you need to start MotherDuck MCP server like this. We use
:memory: as db-path because we want to use in-memory database only. duckdb_client_mcp = MCPClient( lambda: stdio_client(StdioServerParameters( command="uvx", args=["mcp-server-motherduck", "--db-path", ":memory:"], env=get_aws_credentials() )) )And query data like this:
with duckdb_client_mcp: tools = duckdb_client_mcp.list_tools_sync() agent = Agent( tools=tools, system_prompt="You are a data analyst and you can analyze structured data from files.", model=model ) try: logger.info(f"Received query: {user_query}") result = agent(f"Use data from {file_name} to find the answer to the query below\n\n{user_query}") logger.info(f"Agent response: {result.message['content'][0]['text']}") return jsonify({ "response": result.message['content'][0]['text'], "metrics": { "input_tokens": result.metrics.accumulated_usage.get('inputTokens', 0), "output_tokens": result.metrics.accumulated_usage.get('outputTokens', 0), "execution_time": round(sum(result.metrics.cycle_durations), 2), "tools_used": list(result.metrics.tool_metrics.keys()) } }) except Exception as e: logger.error(f"Error processing query: {str(e)}") return jsonify({"error": str(e)}), 500 Now, when ECS service is up and running we can ask our agent about the data we have:
POST http://<YOUR_ALB>/query Content-Type: application/json { "query": "Which stocks performed better over whole time period? Return me top 3 stocks with their return %. Return only stock tickers, price range and return %."}and get answer like this
{ "metrics": { "execution_time": 4.39, "input_tokens": 4310, "output_tokens": 822, "tools_used": [ "query" ] }, "response": "Based on the analysis of the stock price data from January 2014 to December 2017, here are the top 3 performing stocks:\n\n**Top 3 Best Performing Stocks:**\n\n1. **NVDA** (NVIDIA)\n - Price Range: $15.86 - $193.50\n - Return: **1,120.05%**\n\n2. **AVGO** (Broadcom)\n - Price Range: $52.65 - $256.90\n - Return: **387.94%**\n\n3. **EA** (Electronic Arts)\n - Price Range: $22.83 - $105.06\n - Return: **360.18%**\n\nNVIDIA was by far the best performer with an extraordinary return of over 1,100%, likely driven by the AI and cryptocurrency boom during this period. Broadcom and Electronic Arts also delivered exceptional returns of nearly 400% each over the ~4-year period."}for most curious of you, here are the queries, which MotherDuck MCP server executed against our data
[motherduck] INFO - Calling tool: query::{'query': "SELECT * FROM 's3://<YOUR_S3_BUCKET>/<YOUR_FILE>.csv' LIMIT 5"}
[motherduck] INFO - Calling tool: query::{'query': "SELECT \n MIN(date) as start_date,\n MAX(date) as end_date,\n COUNT(DISTINCT symbol) as num_stocks,\n COUNT(*) as total_records\nFROM 's3://<YOUR_S3_BUCKET>/<YOUR_FILE>.csv'"}
[motherduck] INFO - Calling tool: query::{'query': "WITH stock_performance AS (\n SELECT \n symbol,\n MIN(date) as first_date,\n MAX(date) as last_date,\n FIRST_VALUE(close) OVER (PARTITION BY symbol ORDER BY date ASC) as first_price,\n LAST_VALUE(close) OVER (PARTITION BY symbol ORDER BY date ASC ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) as last_price,\n MIN(close) as min_price,\n MAX(close) as max_price\n FROM 's3://<YOUR_S3_BUCKET>/<YOUR_FILE>.csv'\n GROUP BY symbol, close, date\n),\naggregated_performance AS (\n SELECT \n symbol,\n MIN(first_price) as start_price,\n MAX(last_price) as end_price,\n MIN(min_price) as min_price,\n MAX(max_price) as max_price\n FROM stock_performance\n GROUP BY symbol\n)\nSELECT \n symbol as stock_ticker,\n CONCAT('$', ROUND(min_price, 2), ' - $', ROUND(max_price, 2)) as price_range,\n ROUND(((end_price - start_price) / start_price) * 100, 2) as return_percentage\nFROM aggregated_performance\nORDER BY return_percentage DESC\nLIMIT 3"}And, as you can see, LLM used bit over 5K tokens (combined input/output) to get an answer from > 20MB data set.
Building ECS task image
The Docker image you build for this task, should have uv installed to run the MCP server. You can do it by having this in your Dockerfile:
FROM python:3.11-slim WORKDIR /app # Install system dependencies RUN apt-get update && apt-get install -y \ curl \ && rm -rf /var/lib/apt/lists/* # Install uv RUN pip install uv
COPY requirements.txt . RUN uv pip install --system -r requirements.txtAnd in requirements.txt you should have following dependencies:
strands-agents bedrock-agentcore strands-agents-tools mcp flask flask-cors boto3Conclusion
This simple agent with MotherDuck MCP server demonstrates how to analyze the data without:
a. Feeding it completely to your LLM and thus saving a lot of tokens
b. Inserting this data to relational DB just to be able to analyze it for 1 request
And at the same time data can be analyzed/filtered/aggregated with the help of SQL engine of DuckDB and thus providing accurate and predictable results.
What's next
- When your agents need to use ephemeral data you don't necessarily need to use full-fledged database to use that data. So consider using in-memory DB with MCP server.
- In my example I used data on S3, but even that is not necessary - MCP server can access data from local files, if you run MCP server in same ECS task.
Enjoyed reading this content? Let the author know!
Your likes, comments, shares, and saves help creators reach more builders.
Loading recommendations
Loading article