Skip to content
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
67 changes: 67 additions & 0 deletions src/istat_mcp_server/tools/get_data.py
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,70 @@ def parse_sdmx_to_table(xml_content: str, dataflow_full_id: str) -> str:
return '\n'.join(output_lines)


def filter_tsv_by_time_period(tsv_data: str, start_period: str | None, end_period: str | None) -> str:
"""Filter TSV rows by TIME_PERIOD range (workaround for ISTAT endPeriod+1 bug).

The ISTAT SDMX API returns one extra year beyond the requested endPeriod.
This function filters out rows whose TIME_PERIOD falls outside the requested range.

Args:
tsv_data: TSV string with header row
start_period: Requested start period (e.g. '2024' or '2024-01-01')
end_period: Requested end period (e.g. '2024' or '2024-12-31')

Returns:
Filtered TSV string
"""
if not start_period and not end_period:
return tsv_data

lines = tsv_data.split('\n')
if not lines:
return tsv_data

header = lines[0].split('\t')
if 'TIME_PERIOD' not in header:
return tsv_data

tp_idx = header.index('TIME_PERIOD')

# Extract year as int for comparison
def extract_year(period_str: str) -> int | None:
try:
return int(period_str.split('-')[0][:4])
except (ValueError, IndexError):
return None

start_year = extract_year(start_period) if start_period else None
end_year = extract_year(end_period) if end_period else None

Copilot AI Mar 26, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

filter_tsv_by_time_period claims to filter rows outside the requested [start_period, end_period] range, but the implementation only compares the extracted year (YYYY) and ignores month/day within the same year. This can return out-of-range rows when callers provide more specific periods (e.g., end_period='2024-03-31'), and it may also silently skip filtering if start_period/end_period aren’t parseable into a year. Consider either (a) parsing and comparing full TIME_PERIODs for the supported formats (YYYY, YYYY-MM, YYYY-MM-DD, etc.) or (b) explicitly documenting/renaming this as a year-only filter and logging a warning when the period can’t be parsed.

Copilot uses AI. Check for mistakes.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@copilot apply changes based on this feedback

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in f817dc2. Replaced the year-only extraction with a _parse_period helper that normalises all supported formats — YYYY, YYYY-MM, YYYY-MM-DD, YYYY-Qn (quarterly), and YYYY-Sn/YYYY-Hn (semester) — into (year, start_month, end_month) tuples. The filter now correctly excludes rows that fall outside the requested window at sub-year granularity (e.g. end_period='2024-03-31' removes Q2–Q4 rows). When a period string can't be parsed a warning is logged and that filter bound is skipped; rows with unparseable TIME_PERIOD values are kept. 35 unit tests covering all formats and edge cases were also added.


filtered = [lines[0]]
removed = 0
for line in lines[1:]:
if not line:
continue
parts = line.split('\t')
if len(parts) <= tp_idx:
filtered.append(line)
continue
row_year = extract_year(parts[tp_idx])
if row_year is None:
filtered.append(line)
continue
if start_year and row_year < start_year:
removed += 1
continue
if end_year and row_year > end_year:
removed += 1
continue
filtered.append(line)

if removed:
logger.info(f'filter_tsv_by_time_period: removed {removed} rows outside [{start_period}, {end_period}]')

return '\n'.join(filtered)
Comment on lines +167 to +239

Copilot AI Mar 26, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This new client-side TIME_PERIOD filtering logic doesn’t appear to have tests. Adding unit tests for filter_tsv_by_time_period (e.g., verifying 2024 rows are removed when end_period is 2023, and that the header/other rows are preserved) would help prevent regressions and ensure the ISTAT endPeriod+1 workaround behaves as intended.

Copilot uses AI. Check for mistakes.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@copilot apply changes based on this feedback

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@copilot apply changes based on this feedback

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Already addressed in f817dc2tests/test_get_data.py adds 35 unit tests covering filter_tsv_by_time_period and the underlying _parse_period helper. This includes verifying that 2024 rows are removed when end_period is 2023, that the header is always preserved, and cases for all supported period formats (YYYY, YYYY-MM, YYYY-MM-DD, YYYY-Qn, YYYY-Sn/Hn), plus edge cases for unparseable periods and short rows.



def filter_tsv_by_dimensions(tsv_data: str, dimension_filters: dict[str, list[str]]) -> str:
"""Filter TSV rows by dimension values (client-side, post-API).

Expand Down Expand Up @@ -388,6 +452,9 @@ async def handle_get_data(
if params.dimension_filters:
table_data = filter_tsv_by_dimensions(table_data, params.dimension_filters)

# Step 8b: Filter by TIME_PERIOD (workaround for ISTAT endPeriod+1 bug)
table_data = filter_tsv_by_time_period(table_data, start_period, end_period)

# Step 9: Append curl command and query explanation
curl_info = _build_curl_info(
dataflow_id=params.id_dataflow,
Expand Down
Loading