diff --git a/.claude/skills/pcm-startlist/SKILL.md b/.claude/skills/pcm-startlist/SKILL.md new file mode 100644 index 0000000..25fbf4d --- /dev/null +++ b/.claude/skills/pcm-startlist/SKILL.md @@ -0,0 +1,109 @@ +--- +name: pcm-startlist +description: >- + Build a Pro Cycling Manager (PCM) race startlist and export it as the .xml + file PCM imports. Use when the user wants to create, compose, or generate a + startlist for a PCM race — picking which teams take part and which riders + each team brings. Orchestrates the read-only PCM MCP tools (pcm_query_save, + pcm_search_cyclist) to gather data and pcm_generate_startlist_xml to produce + the file. Triggers on phrases like "startlist", "liste de départ", + "engagés pour la course", "génère le fichier xml de la course X". +--- + +# PCM startlist builder + +Compose a startlist for a Pro Cycling Manager race and write the `.xml` file PCM +imports. This skill owns the *workflow* (find the race, choose teams, choose +riders); the deterministic serialization is delegated to the +`pcm_generate_startlist_xml` MCP tool — never hand-write the XML. + +## Output format (for reference only — the tool emits this) + +```xml + + + + + + +``` + +`` = `DYN_team.IDteam`, `` = `DYN_cyclist.IDcyclist`. The file +name is `STA_race.gene_sz_filename` + `.xml` (e.g. `c0_almeria.xml`) and is +returned by the tool — don't invent it. + +## Workflow + +### 1. Get a save path +Every step reads a `.cdb` save. If the user hasn't given an absolute `savePath`: +- Try `pcm_list_saves` (Windows only — fails on macOS/Linux Wine/Proton prefixes). +- Otherwise ask the user for the absolute `.cdb` path. Keep it in context; the + tools are stateless and need it on every call. + +### 2. Identify the race (get `IDrace`) +The user names a race; resolve it to an `IDrace` with `pcm_query_save`: + +```sql +SELECT IDrace, gene_sz_race_name, gene_sz_filename +FROM STA_race +WHERE gene_sz_race_name LIKE '%almeria%'; +``` + +If several match, show the candidates (name + id) and let the user pick. Confirm +the `gene_sz_filename` so the user knows the output file name up front. + +### 3. Decide which teams take part +Either the user supplies the teams, or you propose them. Resolve names to +`IDteam`: + +```sql +SELECT IDteam, gene_sz_name, gene_sz_shortname FROM DYN_team +WHERE gene_sz_name LIKE '%ineos%'; +``` + +A typical startlist has ~18–25 teams. If the user just says "the usual teams", +ask which division/tier or list candidates rather than guessing. + +### 4. Pick riders per team +A team's full squad is the candidate pool — a startlist usually brings **7** of +them (the count is free; the example pack mixes 6 and 7). Get a team's roster: + +```sql +SELECT IDcyclist, gene_sz_firstname, gene_sz_lastname +FROM DYN_cyclist +WHERE fkIDteam = 34; +``` + +To pick riders that fit the race profile, pull the ratings too (the +`charac_i_*` columns — see `pcm_search_cyclist`, which already surfaces them) and +favour the relevant specialty: sprinters/`charac_i_sprint` for flat finishes, +`charac_i_mountain` for climbs, `charac_i_cobble` for cobbled classics, etc. If +the user has preferences (leaders, exclusions), apply them. Confirm the selection +before generating when there's any ambiguity. + +### 5. Generate the file +Call `pcm_generate_startlist_xml` with `savePath`, `raceId`, and `teams`: + +```json +{ + "savePath": "/abs/path/Career.cdb", + "raceId": 128, + "teams": [ + { "id": 34, "cyclists": [7602, 5996, 1381, 3291, 6342, 3912, 5613] }, + { "id": 25, "cyclists": [6346, 8702, 17152, 15300, 7048, 6433, 15398] } + ] +} +``` + +The tool returns `{ fileName, xml }`. If a team has no riders or `teams` is empty +the tool errors — fix the selection and retry. + +### 6. Deliver +Present the returned `fileName` and `xml`. Offer to write it to disk (e.g. the +user's PCM `Startlists`/race-import folder or the working directory) — the MCP +server is read-only and does not write files, so saving is done outside it. + +## Notes +- All PCM MCP tools are read-only; this workflow never modifies the save. +- IDs, not names, go into the XML — always resolve names to `IDteam`/`IDcyclist` + via the queries above before calling the tool. diff --git a/AGENTS.md b/AGENTS.md index 8e38642..d92daa0 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -28,7 +28,7 @@ src/ index.ts # entrypoint: builds McpServer, registers tools, connects stdio saves.ts # save discovery + validation (listSaves, validateSave, getPcmRoot) save-db.ts # withSaveDb(): open .cdb in-memory, run fn, always close db; getGameDate() - helpers.ts # validResponse / errorResponse → CallToolResult; ageFromYmd() + helpers.ts # validResponse / errorResponse → CallToolResult; ageFromYmd(); buildStartlistXml schemas/ cyclist.ts # shared cyclist ratings: ratingsSchema / ratingsColumns() / mapRatings() tools/ @@ -42,6 +42,7 @@ src/ search-cyclist.ts # pcm_search_cyclist search-team.ts # pcm_search_team query-save.ts # pcm_query_save + generate-startlist-xml.ts # pcm_generate_startlist_xml test/ # vitest specs (test/**/*.test.ts) ``` @@ -49,17 +50,18 @@ test/ # vitest specs (test/**/*.test.ts) All tools are prefixed with `pcm_` and carry `readOnlyHint: true` / `destructiveHint: false` annotations so clients can auto-approve them. -| Tool | Purpose | -| ---------------------- | ---------------------------------------------------------------------------------------------------------------------- | -| `pcm_list_saves` | Discover `.cdb` careers by scanning `Pro Cycling Manager /Cloud` under `%APPDATA%` (**Windows only**). | -| `pcm_select_save` | Validate a `.cdb` path and return metadata. Stateless — the path must be kept in conversation context for later tools. | -| `pcm_get_save_schema` | List all tables (id + name) in a save via `DB_STRUCTURE`. | -| `pcm_get_table_schema` | Inspect one table: columns (name, type, NOT NULL, PK) + row count. | -| `pcm_get_player_info` | Active human player + team (joins `GAM_user` `game_i_active = 1` with `DYN_team`). | -| `pcm_get_team_roster` | Team roster (defaults to active player's team). Joins `DYN_cyclist` with active `DYN_contract_cyclist` + `STA_type_rider`: name, country, age, type, overall, contract end, wage, value, plus per-terrain ratings (flat). Errors on unknown `teamId`. | -| `pcm_search_cyclist` | Search cyclist by first/last name (partial, case-insensitive). | -| `pcm_search_team` | Search team by name (partial, case-insensitive; matches full name and short name). | -| `pcm_query_save` | Run a single read-only `SELECT`/`WITH … SELECT`. Write/DDL rejected; results capped (default 100, max 1000). | +| Tool | Purpose | +| ---------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `pcm_list_saves` | Discover `.cdb` careers by scanning `Pro Cycling Manager /Cloud` under `%APPDATA%` (**Windows only**). | +| `pcm_select_save` | Validate a `.cdb` path and return metadata. Stateless — the path must be kept in conversation context for later tools. | +| `pcm_get_save_schema` | List all tables (id + name) in a save via `DB_STRUCTURE`. | +| `pcm_get_table_schema` | Inspect one table: columns (name, type, NOT NULL, PK) + row count. | +| `pcm_get_player_info` | Active human player + team (joins `GAM_user` `game_i_active = 1` with `DYN_team`). | +| `pcm_get_team_roster` | Team roster (defaults to active player's team). Joins `DYN_cyclist` with active `DYN_contract_cyclist` + `STA_type_rider`: name, country, age, type, overall, contract end, wage, value, plus per-terrain ratings (flat). Errors on unknown `teamId`. | +| `pcm_search_cyclist` | Search cyclist by first/last name (partial, case-insensitive). | +| `pcm_search_team` | Search team by name (partial, case-insensitive; matches full name and short name). | +| `pcm_query_save` | Run a single read-only `SELECT`/`WITH … SELECT`. Write/DDL rejected; results capped (default 100, max 1000). | +| `pcm_generate_startlist_xml` | Build a PCM startlist XML from teams + rosters; derives the file name from `STA_race.gene_sz_filename` for the given `IDrace`. | ## Conventions diff --git a/README.md b/README.md index 484a6d5..259158d 100644 --- a/README.md +++ b/README.md @@ -75,17 +75,18 @@ Auto-discovery via `pcm_list_saves` is therefore **Windows only**. On macOS/Linu All tools are read-only and carry `readOnlyHint: true`, so clients like Claude Desktop can approve them automatically without a confirmation prompt. -| Tool | Description | -| ------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -| **pcm_list_saves** | Discover PCM `.cdb` career save files on this machine by scanning the `Pro Cycling Manager /Cloud` folders under `%APPDATA%` (Windows only). Returns each save's absolute path, file name, last modified date and size (newest first). | -| **pcm_select_save** | Validate that an absolute path points to an existing `.cdb` save file and return its metadata. Stateless — keep the returned path in conversation context to pass to later tools. | -| **pcm_get_save_schema** | List every table inside a `.cdb` save file, with its ID and name, plus the total table count. | -| **pcm_get_table_schema** | Inspect a single table by name. Returns its columns (name, SQL type, NOT NULL and primary key flags) and its row count. Use `pcm_get_save_schema` first to discover available table names. | -| **pcm_get_player_info** | Get the active human player and their team from a save file. Returns the player login plus team details (name, resolved division name, resolved country name, evaluation and manager). | -| **pcm_search_cyclist** | Search for a cyclist by first name and/or last name (case-insensitive partial match). Returns up to 10 matches with all ratings (plain, mountain, medium mountain, downhilling, cobble, time trial, prologue, sprint, acceleration, endurance, resistance, recuperation, hill, baroudeur, current ability) and the resolved country name. `mediumMountain` and `currentAbility` are `null` on saves that pre-date those columns. | -| **pcm_get_team_roster** | List a team's roster (defaults to the active player's team when `teamId` is omitted). Joins DYN_cyclist with its active DYN_contract_cyclist and STA_type_rider; per rider returns name, country, age (derived from birth date and the current game date), rider type, overall ability, contract end year, wage, market value and all per-terrain ability ratings. Ordered by overall ability, highest first. Errors if `teamId` does not exist. | -| **pcm_search_team** | Search for a team by name (case-insensitive partial match against both the full name and short name). Returns up to 10 matches with the resolved division name, country name, evaluation and general manager. | -| **pcm_query_save** | Run a read-only SQL query (`SELECT` / `WITH … SELECT` only) against any table in a save file. Write/DDL statements are rejected. Results are capped (default 100, max 1000 rows). | +| Tool | Description | +| ------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | --- | +| **pcm_list_saves** | Discover PCM `.cdb` career save files on this machine by scanning the `Pro Cycling Manager /Cloud` folders under `%APPDATA%` (Windows only). Returns each save's absolute path, file name, last modified date and size (newest first). | +| **pcm_select_save** | Validate that an absolute path points to an existing `.cdb` save file and return its metadata. Stateless — keep the returned path in conversation context to pass to later tools. | +| **pcm_get_save_schema** | List every table inside a `.cdb` save file, with its ID and name, plus the total table count. | +| **pcm_get_table_schema** | Inspect a single table by name. Returns its columns (name, SQL type, NOT NULL and primary key flags) and its row count. Use `pcm_get_save_schema` first to discover available table names. | +| **pcm_get_player_info** | Get the active human player and their team from a save file. Returns the player login plus team details (name, resolved division name, resolved country name, evaluation and manager). | +| **pcm_search_cyclist** | Search for a cyclist by first name and/or last name (case-insensitive partial match). Returns up to 10 matches with all ratings (plain, mountain, medium mountain, downhilling, cobble, time trial, prologue, sprint, acceleration, endurance, resistance, recuperation, hill, baroudeur, current ability) and the resolved country name. `mediumMountain` and `currentAbility` are `null` on saves that pre-date those columns. | +| **pcm_get_team_roster** | List a team's roster (defaults to the active player's team when `teamId` is omitted). Joins DYN_cyclist with its active DYN_contract_cyclist and STA_type_rider; per rider returns name, country, age (derived from birth date and the current game date), rider type, overall ability, contract end year, wage, market value and all per-terrain ability ratings. Ordered by overall ability, highest first. Errors if `teamId` does not exist. | +| **pcm_search_team** | Search for a team by name (case-insensitive partial match against both the full name and short name). Returns up to 10 matches with the resolved division name, country name, evaluation and general manager. | +| **pcm_query_save** | Run a read-only SQL query (`SELECT` / `WITH … SELECT` only) against any table in a save file. Write/DDL statements are rejected. Results are capped (default 100, max 1000 rows). | +| **pcm_generate_startlist_xml** | Generate a PCM startlist XML document from a list of teams and their cyclist rosters. Looks up the race by `IDrace` in the save to derive the output file name from `STA_race.gene_sz_filename` (e.g. `c0_almeria.xml`), and returns both the file name and the XML as text. Team and cyclist IDs map to `DYN_team.IDteam` / `DYN_cyclist.IDcyclist` (look them up with `pcm_search_cyclist` or `pcm_query_save`). | | ## Development diff --git a/src/helpers.ts b/src/helpers.ts index d3d9e4f..8f9ec33 100644 --- a/src/helpers.ts +++ b/src/helpers.ts @@ -30,6 +30,36 @@ export function errorResponse(error: string): CallToolResult { }; } +export interface StartlistTeam { + id: number; + cyclists: number[]; +} + +/** + * Build a Pro Cycling Manager startlist XML document from a list of teams and + * their cyclist rosters. The output mirrors PCM's expected format: a + * `` root, `` children (4-space indent) and + * self-closing `` elements (8-space indent). + */ +export function buildStartlistXml(teams: StartlistTeam[]): string { + if (teams.length === 0) { + throw new Error("Provide at least one team."); + } + const lines: string[] = [""]; + for (const team of teams) { + if (team.cyclists.length === 0) { + throw new Error(`Team ${team.id} has no cyclists.`); + } + lines.push(` `); + for (const cyclistId of team.cyclists) { + lines.push(` `); + } + lines.push(" "); + } + lines.push(""); + return `${lines.join("\n")}\n`; +} + /** Compute age in whole years from two YYYYMMDD integers (e.g. 20030503). */ export function ageFromYmd(currentYmd: number, birthYmd: number): number { let age = Math.floor(currentYmd / 10000) - Math.floor(birthYmd / 10000); diff --git a/src/tools/generate-startlist-xml.ts b/src/tools/generate-startlist-xml.ts new file mode 100644 index 0000000..ab1834b --- /dev/null +++ b/src/tools/generate-startlist-xml.ts @@ -0,0 +1,93 @@ +import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; +import { z } from "zod"; +import { buildStartlistXml } from "../helpers"; +import { withSaveDb } from "../save-db"; + +const outputSchema = z.object({ + fileName: z + .string() + .describe( + "Suggested file name for the startlist, derived from STA_race.gene_sz_filename (e.g. `c0_almeria.xml`)", + ), + xml: z.string().describe("Generated PCM startlist XML document"), +}); + +export function registerGenerateStartlistXml(server: McpServer): void { + server.registerTool( + "pcm_generate_startlist_xml", + { + title: "Generate PCM startlist XML", + description: + 'Generate a Pro Cycling Manager startlist XML document from a list of teams and their cyclist rosters. Looks up the race in the `.cdb` save by `IDrace` to derive the output file name from `STA_race.gene_sz_filename` (e.g. `c0_almeria.xml`). Returns both the file name and the XML as text. The XML is a `` root containing `` elements, each with self-closing `` children. Team and cyclist IDs map to the PCM `DYN_team.IDteam` and `DYN_cyclist.IDcyclist` columns and can be looked up with `pcm_search_cyclist` or `pcm_query_save`. The number of cyclists per team is free.', + inputSchema: { + savePath: z.string().describe("Absolute path to the .cdb save file"), + raceId: z + .number() + .int() + .describe( + "Race ID (STA_race.IDrace) used to derive the output file name", + ), + teams: z + .array( + z.object({ + id: z + .number() + .int() + .describe("Team ID (PCM DYN_team.IDteam / fkIDteam)"), + cyclists: z + .array(z.number().int()) + .describe( + "Cyclist IDs (DYN_cyclist.IDcyclist) for this team's roster", + ), + }), + ) + .describe( + "Teams entered in the race, each with its roster of cyclist IDs", + ), + }, + outputSchema, + annotations: { + readOnlyHint: true, + destructiveHint: false, + idempotentHint: true, + openWorldHint: false, + }, + }, + async ({ savePath, raceId, teams }) => + withSaveDb(savePath, (db) => { + const stmt = db.prepare( + "SELECT gene_sz_filename FROM STA_race WHERE IDrace = :raceId", + ); + let filenameBase: string; + try { + stmt.bind({ ":raceId": raceId }); + if (!stmt.step()) { + throw new Error(`No race found with IDrace ${raceId} in STA_race.`); + } + const value = stmt.getAsObject().gene_sz_filename; + if (value == null || String(value).length === 0) { + throw new Error(`Race ${raceId} has no gene_sz_filename.`); + } + filenameBase = String(value); + } finally { + stmt.free(); + } + + const output: z.infer = { + fileName: resolveStartlistFileName(filenameBase), + xml: buildStartlistXml(teams), + }; + return output; + }), + ); +} + +/** + * Resolve the startlist file name for a race from its `STA_race` row. + * + * PCM stores the base name in `STA_race.gene_sz_filename` (e.g. `c0_almeria`); + * the startlist file is that base name with a `.xml` extension. + */ +export function resolveStartlistFileName(filenameBase: string): string { + return filenameBase.endsWith(".xml") ? filenameBase : `${filenameBase}.xml`; +} diff --git a/src/tools/index.ts b/src/tools/index.ts index 32b8394..5221cb5 100644 --- a/src/tools/index.ts +++ b/src/tools/index.ts @@ -7,6 +7,7 @@ import { registerGetPlayerInfo } from "./get-player-info"; import { registerGetTeamRoster } from "./get-team-roster"; import { registerQuerySave } from "./query-save"; import { registerSearchCyclist } from "./search-cyclist"; +import { registerGenerateStartlistXml } from "./generate-startlist-xml"; import { registerSearchTeam } from "./search-team"; export function registerTools(server: McpServer): void { @@ -18,5 +19,6 @@ export function registerTools(server: McpServer): void { registerGetTeamRoster(server); registerQuerySave(server); registerSearchCyclist(server); + registerGenerateStartlistXml(server); registerSearchTeam(server); } diff --git a/test/generate-startlist-xml.test.ts b/test/generate-startlist-xml.test.ts new file mode 100644 index 0000000..45c9bf4 --- /dev/null +++ b/test/generate-startlist-xml.test.ts @@ -0,0 +1,76 @@ +import { describe, expect, it } from "vitest"; +import { buildStartlistXml } from "../src/helpers"; +import { resolveStartlistFileName } from "../src/tools/generate-startlist-xml"; + +describe("buildStartlistXml", () => { + it("builds XML for a single team", () => { + const xml = buildStartlistXml([{ id: 34, cyclists: [7602, 5996] }]); + expect(xml).toBe( + [ + "", + ' ', + ' ', + ' ', + " ", + "", + "", + ].join("\n"), + ); + }); + + it("builds XML for multiple teams with variable roster sizes", () => { + const xml = buildStartlistXml([ + { id: 34, cyclists: [1, 2, 3, 4, 5, 6, 7] }, + { id: 81, cyclists: [10, 11, 12, 13, 14, 15] }, + ]); + expect(xml).toBe( + [ + "", + ' ', + ' ', + ' ', + ' ', + ' ', + ' ', + ' ', + ' ', + " ", + ' ', + ' ', + ' ', + ' ', + ' ', + ' ', + ' ', + " ", + "", + "", + ].join("\n"), + ); + }); + + it("ends the document with a trailing newline", () => { + const xml = buildStartlistXml([{ id: 1, cyclists: [1] }]); + expect(xml.endsWith("\n")).toBe(true); + }); + + it("throws when no team is provided", () => { + expect(() => buildStartlistXml([])).toThrow("Provide at least one team."); + }); + + it("throws when a team has no cyclists", () => { + expect(() => buildStartlistXml([{ id: 34, cyclists: [] }])).toThrow( + "Team 34 has no cyclists.", + ); + }); +}); + +describe("resolveStartlistFileName", () => { + it("appends .xml to the STA_race base name", () => { + expect(resolveStartlistFileName("c0_almeria")).toBe("c0_almeria.xml"); + }); + + it("does not double-append when .xml is already present", () => { + expect(resolveStartlistFileName("c0_almeria.xml")).toBe("c0_almeria.xml"); + }); +});