deadwax
Deadwax
Агентный музыкальный библиотекарь для личной истории прослушиваний. Он отвечает на вопросы на естественном языке о том, что вы слушали, и собирает плейлисты с учётом жёстких ограничений — с детерминированным валидатором, циклом восстановления и набором для оценки, который сообщает показатели успешных прохождений, а не просто «прошло/не прошло».
Создан как портфолио-проект, демонстрирующий практику промышленной разработки LLM: использование инструментов, поиск, трассировку, оценку и MCP.
Самое интересное
Большинство LLM-демо работают, пока не запустишь их дважды. Deadwax построен вокруг того, что происходит при втором запуске.
Система разделена одной линией: модель никогда не вычисляет. Она интерпретирует язык, выбирает инструменты и составляет прозу. Каждая арифметическая операция, проверка порогов и разрешение ограничений выполняются в обычном Python, который понятия не имеет о существовании LLM. Когда плейлист нарушает ограничение, валидатор не возвращает False — он возвращает код нарушения, идентификаторы треков-нарушителей и конкретное исправление, и только поэтому автоматический цикл восстановления вообще может работать.
Выполнимость проверяется до генерации. Если бриф невозможно удовлетворить, система прямо об этом говорит. Она никогда не дополняет, не подменяет и не деградирует молча — status="infeasible" — это корректный результат со своими собственными оценочными кейсами.
Related MCP server: YouTube Music MCP Server
Правила архитектуры
Это не стилистические предпочтения. Нарушение любого из этих правил сводит на нет цель проекта.
Модель никогда не вычисляет.
Описания инструментов — это управление поведением: они являются промптами, а не документацией. Изменение любого из них — это изменение поведения, и оно переоценивается перед слиянием.
Нарушения должны быть машинообрабатываемыми: код, идентификаторы нарушителей, исправление. Никогда — голое булево значение, никогда — только проза.
Выполнимость проверяется до генерации.
Неудача — допустимый результат.
Жёсткие ограничения измеряются и обеспечиваются. Мягкие ограничения выводятся и оцениваются и несут поле
provenance, которое должно быть раскрыто в любом сообщении о них.Ни одного вызова модели без трассировки.
Решения и их компромиссы задокументированы в docs/adr.
Стек
Всё работает на бесплатном тарифе. Это жёсткое ограничение, а не предпочтение.
Слой | Выбор |
Язык | Python 3.13 |
Инструменты | uv для зависимостей и самого Python, ruff для линтинга и форматирования, pytest |
Агент | LangChain, появляется на этапе 3 и не раньше |
Модель | Google Gemini Flash, с запасным вариантом OpenRouter |
Хранилище | SQLite через модуль стандартной библиотеки |
Поиск | Эмбеддинги на этапе сборки, косинусная близость на чистом Python — без векторной базы данных |
Трассировка | Langfuse |
Взаимодействие | сервер Model Context Protocol |
Фронтенд | Astro на Cloudflare Pages — единственный JavaScript-компонент |
Этапы с 0 по 2 используют только стандартную библиотеку — никаких фреймворков, SDK и зависимостей. Сырой HTTP-вызов пишется вручную до введения каких-либо абстракций, чтобы, когда фреймворк искажает то, что он делает, разница была видна.
Ход разработки
Двенадцать этапов, четыре фазы. Одна ветка и один PR со squash-merge на каждый этап, так что история читается так, как реально шла разработка.
Фаза | Этап | Статус |
A · Основа | 0 · Один сырой вызов | 🔨 в процессе |
A · Основа | 1 · Тестовые данные | ⬜ |
A · Основа | 2 · Детерминированное ядро | ⬜ |
B · Агент | 3 · Первый цикл инструментов | ⬜ |
B · Агент | 4 · Измерить нестабильность | ⬜ |
B · Агент | 5 · Оценочный стенд | ⬜ |
C · Доводка | 6 · Цикл восстановления | ⬜ |
C · Доводка | 7 · Состязательные случаи | ⬜ |
C · Доводка | 8 · Трассировка | ⬜ |
C · Доводка | 9 · Поиск | ⬜ |
D · Релиз | 10 · Реальные данные | ⬜ |
D · Релиз | 11 · MCP-сервер | ⬜ |
D · Релиз | 12 · Сайт и статья | ⬜ |
Запуск
Вам понадобится uv. Он устанавливает и управляет самим Python, так что это единственное необходимое условие.
winget install --id=astral-sh.uv -eЗатем, из корня репозитория:
uv syncЭто создаёт виртуальное окружение, устанавливает зафиксированную версию Python из .python-version и устанавливает проект.
Добавьте бесплатный API-ключ Gemini из Google AI Studio:
copy .env.example .envВставьте ключ после GEMINI_API_KEY=. Затем посмотрите, к каким моделям ваш ключ имеет доступ, поскольку каталоги бесплатного тарифа меняются без предупреждения:
uv run scripts/raw_call.py --listПоместите один из этих идентификаторов в .env как GEMINI_MODEL и выполните вызов:
uv run scripts/raw_call.pyОн выводит полный запрос и полный ответ перед извлечением ответа. В этом и смысл скрипта — структуры стоит знать, прежде чем фреймворк их скроет.
Фактические лимиты запросов вашего аккаунта показаны на aistudio.google.com/rate-limit; Google больше не публикует таблицу бесплатных тарифов по моделям в документации API.
Оценка
Оценочный набор появляется на этапе 5. Кейсы пишутся вручную и никогда не генерируются — если один и тот же инструмент пишет и код, и оценку, результат ничего не значит. Результаты сообщаются как доля успешных прохождений по множественным запускам, потому что единственное успешное прохождение на недетерминированной системе — это анекдот.
Любой коммит, который меняет промпт, описание инструмента или модель, должен содержать в сообщении оценки до/после.
Лицензия
MIT. См. LICENSE.
Создано David Koen.
Available Tools
4 toolscheck_feasibilityARead-only
Check whether a playlist brief is possible at all, before choosing any tracks.
Call this first, before query_library, whenever the user asks for a playlist with constraints. If feasible is false the brief cannot be satisfied by this library: tell the user which constraint fails and stop. Do not build a playlist anyway, do not relax the constraint yourself, and do not try alternative track combinations.
max_achievable_display is the longest playlist the library can produce under these constraints. When explaining a refusal, describe what the user asked for in their own words and quote max_achievable_display for what is possible. Never show the user a millisecond figure and never convert one yourself.
A brief with no constraints at all cannot be checked. If the user has not said how long the playlist should be or what should be in it, ask them before calling this.
| Name | Required | Description | Default |
|---|---|---|---|
| released_after | No | ||
| released_before | No | ||
| required_genres | No | ||
| max_track_duration_ms | No | ||
| max_tracks_per_artist | No | ||
| min_total_duration_ms | No |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
Annotations already declare a safe read-only, closed-world operation, and the description goes well beyond them: it discloses the 'feasible' boolean and 'max_achievable_display' return semantics, plus a refusal protocol and a presentation rule (never surface or convert millisecond figures). That is real behavioral context an agent could not infer from readOnlyHint alone.
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?
Front-loaded with the core purpose and the sequencing rule, and most sentences add distinct policy. The refusal paragraph slightly over-enumerates ('do not build a playlist anyway, do not relax the constraint yourself, and do not try alternative track combinations'), which are three phrasings of one instruction.
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 six-parameter, no-output-schema tool the usage and refusal policy are complete, but the description omits any explanation of the parameter formats an agent must supply, which is the main remaining risk. It explains two return fields but not the full result shape.
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 carries the full burden for six parameters, yet it never explains any of them. It is ambiguous whether released_after/released_before are years or epoch timestamps, and units for max_track_duration_ms and min_total_duration_ms are only obliquely implied by the millisecond warning.
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?
States a specific verb and resource ('check whether a playlist brief is possible') and positions it temporally ahead of track selection, which distinguishes it from query_library and validate_playlist. An agent knows immediately that this is a pre-flight gate, not a builder or validator.
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?
Explicit when-to-call ('first, before query_library, whenever the user asks for a playlist with constraints'), explicit when-not ('a brief with no constraints at all cannot be checked — ask them before calling'), and explicit failure behavior ('tell the user which constraint fails and stop', 'do not relax the constraint yourself'). Alternatives and exclusions are both covered.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
enrich_artistARead-only
Look up background on one artist in the user's library, from published sources.
Call this for any question about an artist's history, members, origins, influences or career. Pass the artist's name and the user's question. It returns the passages from MusicBrainz and Wikipedia that best match the question.
Answer only from these passages. If they do not contain the answer, tell the user your sources do not cover it, even if you believe you know. Never fill the gap from your own knowledge.
Cite every passage you use by its id in square brackets, such as [can-03], straight after the claim it supports. Never cite an id this tool did not return.
This tool knows nothing about the user's tracks. Use query_library for those.
| Name | Required | Description | Default |
|---|---|---|---|
| artist | Yes | ||
| question | Yes |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
Goes well beyond the readOnly/openWorld annotations by disclosing the data sources (MusicBrainz, Wikipedia), the grounding contract (answer only from returned passages, refuse otherwise), and the citation protocol required in the reply. These are response-shaping rules the annotations cannot convey.
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?
Front-loaded with purpose, then usage, then output contract, then sibling routing. Every sentence adds an actionable rule; nothing is redundant with the schema or annotations.
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?
No output schema exists, and the description supplies the return shape ('passages ... that best match the question') along with the id format used in citations. An agent has everything needed to call it and to post-process the result correctly.
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 coverage is 0%, so the description must compensate, and it does: 'artist' is clarified as the name and 'question' as the user's question, which implies phrasing the question in natural language rather than keywords. It stops short of format examples or naming conventions for the artist string.
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?
States a specific verb and resource ('look up background on one artist ... from published sources') and names the sources. The final sentence explicitly separates it from query_library, so an agent can route without opening the schema.
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?
Gives an explicit trigger ('any question about an artist's history, members, origins, influences or career') and an explicit exclusion plus alternative ('This tool knows nothing about the user's tracks. Use query_library for those.'). Both when and when-not are covered.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
query_libraryARead-only
Search the user's music library and return matching tracks with their totals.
Call this before stating any fact about the library. Never estimate a count, a duration or a track name from your own knowledge, and never add numbers up yourself: use total_matching and total_duration_ms from the result, which are computed exactly. The tracks list is truncated to limit entries, so it may be shorter than total_matching.
To find a longest, shortest, highest or lowest track, pass order_by as one of longest, shortest, highest_energy, lowest_energy and read the first entry. Never rank, compare or pick a maximum out of the list yourself; the ordering is computed here.
Quote duration_display for a track and total_duration_display for a set of them. Never convert milliseconds to minutes yourself.
Energy is an estimate, not a measurement. Every track carries energy_provenance saying where its value came from, and any answer that mentions energy must say it is an estimate.
If a genre search finds nothing, known_genres lists the genre tags the library actually uses. If the user's word is another name for one of them, as rap is for hip hop, search again with that tag and say which tag you searched. Never substitute a genre that is merely related.
| Name | Required | Description | Default |
|---|---|---|---|
| genre | No | ||
| limit | No | ||
| artist | No | ||
| played | No | ||
| order_by | No | ||
| released_after | No | ||
| max_duration_ms | No | ||
| min_duration_ms | No | ||
| released_before | No |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
Annotations already establish read-only and non-destructive behavior, but the description adds substantial behavioral context beyond that: the tracks list is truncated to limit, totals are computed exactly, ordering is computed server-side, energy is an estimate with provenance, and genre fallback is available. These details materially change how an agent should interpret and present results.
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 front-loaded with the core action and key rules, and most sentences carry actionable guidance. It is somewhat long and repeats the same anti-estimation theme across multiple sentences, which costs some conciseness, but the structure remains purposeful.
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?
There is no output schema, so the description appropriately explains key return fields such as total_matching, total_duration_ms, tracks, duration_display, and energy_provenance. However, for a 9-parameter tool with 0% schema description coverage, it leaves important input filters undocumented, so the overall context is only partially complete.
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 there are 9 parameters, so the description must carry the burden of explaining them. It adds meaning for order_by values, genre fallback behavior, and limit truncation, but it does not explain artist, played, released_after, released_before, min_duration_ms, or max_duration_ms, leaving more than half of the parameters undocumented.
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 states a specific verb and resource: search the user's music library and return matching tracks with totals. It is immediately distinguishable from the sibling tools validate_playlist, enrich_artist, and check_feasibility, which serve different purposes.
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?
It gives explicit usage rules: call before stating any fact about the library, never estimate counts or durations, use total_matching and total_duration_ms, and pass order_by for longest/shortest/highest/lowest queries. It also explains the genre fallback path and when to search again with known_genres. The guidance is unusually complete for an agent.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
validate_playlistARead-only
Check a proposed playlist against hard constraints and report every violation.
Call this before presenting any playlist to the user. Do not judge for yourself whether a playlist meets its constraints. Each violation names the offending track ids and an adjust_by amount in the constraint's own unit: negative means remove that much, positive means add that much. Act on adjust_by rather than guessing how much to change.
When describing the playlist, quote track_count and total_duration_display from this result verbatim. Never sum durations yourself and never convert milliseconds to minutes yourself.
A duration violation also carries adjust_by_display, the same amount written in minutes and seconds. Show the user that, never the millisecond figure.
Pass the same release-year bounds you gave check_feasibility, so a track outside the window is caught here too.
If the user asks for an energy level or a mood, pass target_energy between 0 and 1. It is scored, never enforced: soft_scores reports how close the playlist came, and because energy is estimated rather than measured, any answer that mentions it must say so.
| Name | Required | Description | Default |
|---|---|---|---|
| track_ids | Yes | ||
| target_energy | No | ||
| released_after | No | ||
| released_before | No | ||
| required_genres | No | ||
| max_total_duration_ms | No | ||
| max_track_duration_ms | No | ||
| max_tracks_per_artist | No | ||
| min_total_duration_ms | No |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
Annotations already establish that this is a safe read (readOnlyHint=true, destructiveHint=false), and the description adds substantive behavior the annotations cannot convey: violation records carry track ids and a signed adjust_by in the constraint's unit, duration violations also carry adjust_by_display, and target_energy is scored rather than enforced. It also warns that energy is estimated and must be disclosed, which is a real behavioral constraint on downstream answers.
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 most important directive (what the tool does, and call it before presenting) is front-loaded, and every subsequent paragraph carries a distinct instruction: adjust_by semantics, verbatim quoting rules, cross-tool bound reuse, and energy caveat. It is on the long side for a nine-parameter tool, but no sentence is redundant.
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?
With no output schema, the description has to sketch the return shape and it does: violations, adjust_by, adjust_by_display, soft_scores, track_count, total_duration_display. The remaining gap is the unmentioned constraint parameters, which an agent must guess from their names alone.
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 carries the full burden. It explains target_energy well (0-1 range, scored not enforced, soft_scores output) and gives intent for released_after/released_before by tying them to check_feasibility, but required_genres, max_total_duration_ms versus min_total_duration_ms, max_track_duration_ms, and max_tracks_per_artist are never mentioned — half the parameters remain opaque.
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?
States a specific verb and resource (check a proposed playlist against hard constraints) plus the scope of the output (report every violation). It implicitly separates itself from check_feasibility by instructing the caller to reuse the release-year bounds given to that sibling, so an agent can tell the two apart.
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?
Explicit temporal gating ('Call this before presenting any playlist', 'Do not judge for yourself'), an explicit cross-tool dependency ('Pass the same release-year bounds you gave check_feasibility'), and an explicit conditional trigger ('If the user asks for an energy level or a mood, pass target_energy'). Nothing is left to inference.
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.
4 tool updates
v0.1.0- First observed
check_feasibility - First observed
enrich_artist - First observed
query_library - First observed
validate_playlist
TDQS
Scored across 4 tools
Each tool has a clearly distinct role: check_feasibility checks a brief before track selection, query_library searches local tracks, validate_playlist checks a proposed playlist, and enrich_artist retrieves external artist background. The descriptions explicitly distinguish the two check-style tools by workflow phase and data source.
All four names follow a consistent snake_case verb_noun pattern: validate_playlist, enrich_artist, check_feasibility, query_library. The verbs are distinct and predictable for their actions.
Four tools is well-scoped for a focused playlist-assistant server, with each tool covering a separate workflow stage. There is no redundant or filler tool.
The set covers feasibility checking, library search, playlist validation, and artist enrichment, which supports the core playlist-building workflow. Minor gaps remain around explicitly creating, saving, or exporting a playlist, but agents can work around this by presenting validated playlists.
Maintenance
Related MCP Connectors
Autonomous music production for AI agents with MIDI generation, QC and provenance.
Builds narrated, playable music stories, explores sample lineage, and saves verified playlists.
AI playlist engine that turns music prompts into real YouTube playlists and filters bad versions.
Deterministic music theory for agents: analyze, voice, reharmonize, conduct — computed, not guessed
Related MCP Servers
- AlicenseBqualityAmaintenanceAnalyze listening patterns, create custom playlists, discover missing albums, validate radio streams, and provide personalized recommendations through natural language.264 npm93AGPL 3.0
- AlicenseNot gradedqualityDmaintenanceEnables AI assistants to search YouTube Music, manage playlists, and create smart recommendations using natural language.15MIT
- AlicenseNot gradedqualityCmaintenanceEnables natural-language querying and control of a Lyrion Music Server, including music library searches, album playback, player controls, and play-history tracking.2MIT
- AlicenseAqualityBmaintenanceEnables MCP clients to build and edit Spotify playlists from natural language descriptions.752 npmMIT