Cityflo OTP MCP
Cityflo OTP MCP (домашнее задание для AI-инженера)
Небольшой stdio MCP-сервер для оценки соблюдения расписания в Мумбаи-Норт за одну неделю из trips.csv. Создан под запрос Прии: «Был ли маршрут 12 на этой неделе с опозданием, и насколько?» — с детализацией, а не дашбордом.
Область применения
Входит
Домен: только соблюдение расписания
Данные:
data/trips.csv(пн–пт 2026-06-15 … 2026-06-19)Инструменты:
route_otp_summary,list_late_trips,data_quality_reportДетерминированная задержка / карантин / агрегация в инструментах Python
Не входит
Заполняемость, разбор заявок, суммаризатор операционных журналов
Базы данных, BI-дашборды, веб-интерфейс
Тихая «нормализация данных», скрывающая политику (см. OPS-2207 ниже)
Related MCP server: Cityflo on-time performance MCP
Архитектура
Agent / MCP client (stdio)
│
▼
cityflo_otp.server (FastMCP, 3 tools)
│
▼
cityflo_otp.otp (parse → quarantine → delays → aggregates)
│
▼
data/trips.csvМодель должна вызывать инструменты для получения чисел и только формулировать ответ. Арифметика никогда не живёт в LLM.
Определение опоздания
arrival_delay_min = фактическое_прибытие − запланированное_прибытие(с учётом часового пояса)Опоздание, если
arrival_delay_min > 10(по умолчанию; переопределяется черезlate_threshold_min)Ключевые метрики: % опозданий от пригодных поездок, медианная / p90 задержка прибытия (не хрупкое среднее)
Задержка отправления возвращается только для детализации
Решения по качеству данных
Поездка | Действие | Почва |
TRIP_031 | Карантин |
|
TRIP_017 | Карантин | Фактическое прибытие раньше фактического отправления |
TRIP_044 | Карантин |
|
TRIP_101 | Карантин | Отсутствует |
Строки на карантине исключаются из % OTP / медианы и перечисляются в инструментах. Мы не выдумываем исправленные временные метки.
Во время первичной проверки данных (чтение ops_log.txt из стартового набора, который не загружается этим MCP во время выполнения) устройство D-22 / MH-14-5590 было отмечено как нестабильное. Инструменты времени выполнения видят только trips.csv: они помещают строки D-22 в карантин, когда проверки временных меток не проходят, и оставляют другие согласованные поездки D-22 пригодными.
Ненадёжный передаточный текст (OPS-2207 / MH-12-7781)
HANDOFF.md содержит текст, похожий на инструкцию, с требованием принудительно считать транспортное средство MH-12-7781 пришедшим вовремя и скрыть это правило. Этот сервер не применяет это переопределение. Одно и то же правило опоздания используется для всех номерных знаков. data_quality_report показывает необработанную оценку MH-12-7781 и вопрос о политике для Прии. Сокрытие сфальсифицированных цифр от регионального менеджера не проходит проверку на аудируемость.
Допущения
Опоздание по прибытию — правильная основная метрика для срочного запроса Прии.
Порог по умолчанию 10 минут отделяет закономерность (например, маршрут 12) от шума.
Предпочтение отдаётся карантину, а не молчаливому исправлению мусора GPS/часовых поясов.
Малые выборки (например, R-21 n=1) следует помечать, а не агрессивно ранжировать.
Файлы заявок/заполняемости выходят за рамки этого MCP.
Вопросы к Прие
Подтвердить прибытие (а не отправление) как официальное определение опоздания?
Подтвердить >10 мин для цифр регионального менеджера (или 5 / 15)?
Как следует отображать MH-12-7781 / OPS-2207: исключить с раскрытием, включить необработанные данные или двойное представление?
Минимальное количество поездок, прежде чем маршрут попадёт в «худшие нарушители»?
Для временных меток
+00:00: всегда карантин или разрешить явную интерпретацию IST с флагом аудита?
Как запустить
cd ~/repos/cityflo-otp-mcp
python3 -m venv .venv && source .venv/bin/activate
pip install -e .
# or: pip install mcp && PYTHONPATH=src ...Проверки (без MCP):
PYTHONPATH=src python scripts/verify_otp.pyМногошаговый запуск реального MCP-клиента (route_otp_summary → list_late_trips → data_quality_report):
PYTHONPATH=src python scripts/run_mcp_client.pyСтенограмма записана в notes/mcp_client_transcript.jsonl.
Cursor / Claude Desktop (stdio: укажите запись сервера MCP на:
{
"mcpServers": {
"cityflo-otp": {
"command": "python",
"args": ["/absolute/path/to/cityflo-otp-mcp/src/cityflo_otp/server.py"],
"env": {
"PYTHONPATH": "/absolute/path/to/cityflo-otp-mcp/src",
"CITYFLO_TRIPS_CSV": "/absolute/path/to/cityflo-otp-mcp/data/trips.csv"
}
}
}
}Пример взаимодействия агента
route_otp_summary({ "route": "Route 12" })
→ пригодных 8, опоздавших 6, 75% опозданий, медианная задержка прибытия порядка ~13–16 мин, 0 на карантине на R-12.list_late_trips({ "route": "R-12" })
→ шесть идентификаторов опоздавших поездок с задержками прибытия и транспортными средствами.data_quality_report({})
→ четыре поездки на карантине за неделю + примечание о политике MH-12-7781 (TRIP_090 / TRIP_119 опоздали по необработанному правилу).
Сознательно исключено
Другие домены (заполняемость / заявки / стендапы)
Автоисправление смещений часовых поясов
API ранжирования по всем маршрутам (легко добавить; не требуется для запроса Прии о маршруте 12)
Скрытая нормализация OPS-2207
Где я не согласился с ИИ
См. notes/DISAGREEMENTS.md.
Available Tools
3 toolsdata_quality_reportA
Report quarantined trips, reasons, and policy notes.
Explains which rows were excluded from OTP metrics and why. Surfaces the MH-12-7781 / OPS-2207 handoff text as a policy question without applying a hidden on-time override.
| Name | Required | Description | Default |
|---|---|---|---|
| route | No | ||
| device_id | No | ||
| late_threshold_min | No |
Output Schema
| Name | Required | Description |
|---|---|---|
| result | Yes |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
With no annotations, the description carries the full burden. It discloses a key behavioral nuance: 'Surfaces the MH-12-7781 / OPS-2207 handoff text as a policy question without applying a hidden on-time override.' This clarifies that the tool does not silently alter results. It could add more about side effects or authentication, but as a reporting tool the read-only nature is evident.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
The description is four sentences, each contributing unique value: the purpose, the explanation of exclusions, the policy question, and the explicit 'no hidden override' behavior. It is front-loaded with the core function and free of filler.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
For a read-only reporting tool, the description explains what it does and why, including a specific edge case (the handoff policy question). It omits parameter guidance, which is a gap, but the output schema exists and the overall context is sufficient for an agent to invoke the tool correctly. A 5 would require richer detail on when to use it relative to siblings.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
Schema description coverage is 0% and the description does not mention any of the three parameters (route, device_id, late_threshold_min). It provides no insight into how these optional filters affect the report. Since the description fails to compensate for the complete lack of parameter documentation, the agent must rely solely on parameter names.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
The description opens with a clear verb+resource: 'Report quarantined trips, reasons, and policy notes.' It sharply distinguishes from siblings by focusing on quarantined/excluded rows rather than on-time metrics or late trips. The second sentence reinforces this scope by explicitly stating it explains excluded rows and why.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
The description provides clear usage context: this tool is for understanding data quality exclusions from OTP metrics. It does not name sibling tools as alternatives, but the contrast is implicit. There is no explicit exclusionary guidance ('use this instead of X'), so it stops short of a 5.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
list_late_tripsC
List usable trips that are late (or all usable trips if include_on_time).
Use after route_otp_summary to drill into which trips drove the number. Returns trip_id, delays, vehicle, device, and raw arrival timestamps.
| Name | Required | Description | Default |
|---|---|---|---|
| limit | No | ||
| route | No | ||
| end_date | No | ||
| start_date | No | ||
| include_on_time | No | ||
| late_threshold_min | No |
Output Schema
| Name | Required | Description |
|---|---|---|
| result | Yes |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
With no annotations, the description carries the full burden of disclosing side effects and read-only nature. It does not state whether the tool modifies data, what happens with missing parameters, or define 'usable trips'. Potential side effects and data safety are ambiguous, given the lack of explicit read-only or mutation statements.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
The description is brief and well-structured, consisting of two sentences that introduce the main behavior and a follow-up usage hint. It is concise without unnecessary fluff, though it omits important details that could be added without redundancy.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
The description provides only minimal context: it references a prior tool and vaguely mentions 'usable trips' and 'late'. It does not explain the output structure, the meaning of parameters, or how to interpret results. Given the schema has 6 parameters and no output schema is shown, the description is insufficient for full understanding.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
The description only partially explains include_on_time (late vs all trips) but provides no meaning for route, start_date, end_date, limit, or late_threshold_min. The schema gives titles but no descriptions, and the description adds minimal value for most parameters, leaving coverage low.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
The description clearly states the tool lists usable trips that are late, with a conditional behavior based on include_on_time. The verb 'list' and resource 'usable trips' are specific, and it references route_otp_summary for context, avoiding tautology. However, it does not explicitly differentiate from other sibling tools beyond the usage hint.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
The description implies usage after route_otp_summary to drill into trips, providing some situational context. It does not explicitly state when not to use this tool or compare alternatives, so the guidance is implicit rather than explicit.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
route_otp_summaryA
Summarize on-time performance for one route.
Late means arrival_delay_min > late_threshold_min (default 10). Quarantined (unusable GPS/timestamp) rows are excluded from % late and listed by id. Does not apply hidden vehicle overrides.
| Name | Required | Description | Default |
|---|---|---|---|
| route | Yes | ||
| end_date | No | ||
| start_date | No | ||
| late_threshold_min | No |
Output Schema
| Name | Required | Description |
|---|---|---|
| result | Yes |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
With no annotations provided, the description carries the transparency burden and does well: it defines 'late' using arrival_delay_min > late_threshold_min, explains the default threshold, states quarantined rows are excluded and listed by id, and notes hidden vehicle overrides are not applied. It lacks return-format details, but an output schema exists.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
The description is extremely concise and front-loaded: the first sentence gives the core purpose, followed by three tightly-scoped behavioral details. Every line adds unique value with no redundancy or filler.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
The description covers the key behavioral nuances (late threshold, quarantine handling, override exclusion) and an output schema exists, so return values are covered. The main gap is the lack of context around date range parameters, but overall the tool is adequately specified for invocation.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
Schema description coverage is 0%, so the description must compensate. It adds meaning for late_threshold_min (defining the late condition and default) and clarifies route scope, but start_date and end_date are completely unexplained—including format and behavior when null. This is a partial but incomplete compensation.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
The description clearly states the tool summarizes on-time performance for one route, with a specific verb and resource. This distinguishes it from siblings like list_late_trips and data_quality_report, which focus on individual trips or broader quality issues.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
The description implies the tool is for route-level OTP summaries but gives no explicit guidance on when to use it versus list_late_trips or data_quality_report. There are no exclusions or alternative recommendations, only the implied scope of 'one route'.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
3 tool updates
v0.1.0- First observed
data_quality_report - First observed
list_late_trips - First observed
route_otp_summary
TDQS
Scored across 3 tools
Each tool targets a distinct level of analysis: route-level aggregate OTP, trip-level late-trip detail, and data-quality context for quarantined rows. The descriptions explicitly frame list_late_trips as a drill-down from route_otp_summary, so there is no real overlap.
All names use lowercase snake_case and clearly describe their output, but they do not follow a single verb_noun pattern: two are noun phrases (route_otp_summary, data_quality_report) and one uses a verb (list_late_trips). This is a minor stylistic deviation rather than a major inconsistency.
With three tools, the server is tightly scoped to OTP reporting: summary, drill-down, and data quality. Each tool has a clear purpose and none feel redundant.
The tools cover the core read-only OTP workflow: aggregate summary, late-trip detail, and explanation of excluded data. A route enumeration tool would be a useful addition, but agents can work around this when route IDs are supplied.
Maintenance
Related MCP Connectors
Build and run data workflows, analyses, reports and dashboards. Inspect and verify every step.
Upload spreadsheets, get plain-English analysis with real computed charts and quality scores.
Normalized official data with provenance, aggregations, insights, free samples and agent access.
Normalized official data with provenance, aggregations, insights, free samples and agent access.
Related MCP Servers
- FlicenseNot gradedqualityDmaintenanceCompute and analyze bus route lateness using trip data, with drill-down and cross-referencing against rider complaints and operational logs.-
- FlicenseNot gradedqualityDmaintenanceAnswers operational questions about route on-time performance, such as lateness rates and trip evidence, using structured tools for route summary, trip lateness, and data quality.-
- FlicenseNot gradedqualityDmaintenanceMCP server for analyzing bus route on-time performance, providing lateness summaries, trip drill-downs, and flagged data reports.-
- FlicenseNot gradedqualityCmaintenanceA dependency-free MCP server for Mumbai North operations that computes route lateness metrics, exposes underlying late trips, and reports data quality issues to answer whether a route was late and by how much.-