How the MCP Airflow API Server Handles Date Calculations for Relative Time Queries
The server calculates relative dates using a single datetime.now() reference point and timedelta arithmetic inside the get_current_time_context() helper, ensuring consistent date calculations across every request.
The call518/mcp-airflow-api repository implements a robust date calculation system for handling relative time queries in MCP (Model Context Protocol) tools. When users ask for data from "yesterday," "last week," or "last 3 days," the server must translate these natural language expressions into concrete ISO-formatted dates. This article examines the exact implementation of these date calculations for relative time queries in the source code.
The Core Date Calculation Engine
All relative date logic resides in get_current_time_context() within src/mcp_airflow_api/functions.py (lines 272–298). This function serves as the single source of truth for time-based calculations across the entire MCP server.
The implementation follows a strict pattern to ensure atomicity:
- Capture once –
datetime.now()is invoked exactly once per function call - Calculate derivatives – All relative dates derive from this single reference point
- Format consistently –
strftime('%Y-%m-%d')produces ISO 8601 date strings
This approach eliminates race conditions where the current date might change between calculating "yesterday" and "last week."
How Relative Dates Are Computed
Capturing the Reference Moment
The function establishes a fixed temporal anchor using Python's standard library:
current_time = datetime.now()
current_date = current_time.strftime('%Y-%m-%d')
By snapshotting datetime.now() into current_time, all subsequent calculations operate against an immutable reference. This ensures that even if the function executes across a midnight boundary, all relative dates remain consistent with the original request time.
Calculating Yesterday and Recent Periods
The server uses timedelta arithmetic to derive relative periods from the reference point:
yesterday = (current_time - timedelta(days=1)).strftime('%Y-%m-%d')
last_week_start = (current_time - timedelta(days=7)).strftime('%Y-%m-%d')
last_week_end = yesterday # Same as yesterday by definition
last_3_days_start = (current_time - timedelta(days=3)).strftime('%Y-%m-%d')
These calculations handle month boundaries, year rollovers, and leap years automatically through Python's datetime implementation.
Formatting for API Consumption
All derived dates follow the strict YYYY-MM-DD format required by the Airflow REST API. The function constructs a human-readable reference string alongside the machine-formatted dates:
reference_date = current_time.strftime('%B %d, %Y (%Y-%m-%d)')
This dual formatting supports both API requests (ISO format) and user-facing prompts (human-readable).
The Date Context Dictionary Structure
The get_current_time_context() function returns a structured dictionary consumed by MCP tools. The mapping includes:
current_date– ISO-formatted date string (YYYY-MM-DD)current_time– ISO-formatted datetime string (YYYY-MM-DD HH:MM:SS)reference_date– Human-readable date with ISO fallbackdate_calculation_examples– Nested dictionary containing:yesterdaylast_week_startlast_week_endlast_3_days_start
Tools access these values to replace template placeholders like {{yesterday}} or {{last_week_start}} with concrete dates at request time.
Integration with MCP Tools
The date calculation system integrates with the broader MCP server architecture through src/mcp_airflow_api/tools/common_tools.py. This module imports get_current_time_context() (line 10) and makes it available to all registered tools.
When the server starts via the entry point (typically mcp_main.py), it registers common tools that depend on this date context. Each incoming request triggers a fresh call to get_current_time_context(), ensuring that relative time calculations always reflect the actual server time rather than cached values.
Practical Implementation Examples
Example 1: Direct Usage of the Helper
from mcp_airflow_api.functions import get_current_time_context
ctx = get_current_time_context()
print(ctx["date_calculation_examples"]["yesterday"])
# Output: 2026-02-25 (assuming execution date is 2026-02-26)
Example 2: Tool Accepting Relative Time Labels
async def get_tasks_started_since(label: str):
"""
label: One of 'yesterday', 'last_week', 'last_3_days'
"""
ctx = get_current_time_context()
examples = ctx["date_calculation_examples"]
mapping = {
"yesterday": examples["yesterday"],
"last_week": examples["last_week_start"],
"last_3_days": examples["last_3_days_start"]
}
start_date = mapping.get(label)
if not start_date:
raise ValueError(f"Unsupported relative label: {label}")
resp = await airflow_request(
"GET",
f"/tasks?started_after={start_date}"
)
resp.raise_for_status()
return resp.json()
Example 3: Rendering Templates with Relative Dates
template = """
Execution Report for {{reference_date}}:
- Yesterday's data: {{yesterday}}
- Last week range: {{last_week_start}} to {{last_week_end}}
- Last 3 days from: {{last_3_days_start}}
"""
ctx = get_current_time_context()
examples = ctx["date_calculation_examples"]
# Simple template substitution
rendered = template.replace("{{reference_date}}", ctx["reference_date"])
for key, val in examples.items():
rendered = rendered.replace(f"{{{{{key}}}}}", val)
print(rendered)
Summary
get_current_time_context()insrc/mcp_airflow_api/functions.py(lines 272–298) serves as the central engine for all date calculations for relative time queries.- The function uses a single
datetime.now()snapshot to ensure consistency across derived dates like yesterday, last week, and last 3 days. - Timedelta arithmetic handles all date math, automatically managing month boundaries and leap years.
- The returned context dictionary provides both machine-readable ISO dates and human-readable formats for MCP tool consumption.
- Integration through
common_tools.pyensures all server tools access fresh, request-time date calculations.
Frequently Asked Questions
What function handles date calculations for relative time queries in the MCP Airflow API?
The get_current_time_context() function defined in src/mcp_airflow_api/functions.py (lines 272–298) handles all date calculations. It returns a dictionary containing the current date, reference timestamps, and pre-computed relative dates like yesterday and last week.
How does the server ensure consistent dates across a single request?
The server captures datetime.now() exactly once at the start of get_current_time_context(). All relative dates (yesterday, last week, last 3 days) derive from this single timestamp using timedelta arithmetic, preventing inconsistencies that could occur if the clock rolled over to a new day during execution.
What relative time periods are supported by default?
The default implementation supports yesterday, last week (7 days ago), and last 3 days (3 days ago). Specifically, the date_calculation_examples dictionary includes keys for yesterday, last_week_start, last_week_end, and last_3_days_start.
Can I extend the date calculations to support custom relative periods?
Yes. Since get_current_time_context() uses standard Python timedelta operations, you can extend the function to include additional calculations like timedelta(weeks=2) for "last 2 weeks" or timedelta(hours=6) for "6 hours ago". The context dictionary structure allows easy addition of new keys to date_calculation_examples for use in tool templates.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →