Skip to main content
Glama

mcp-server-and-agent

Ручной MCP-сервер на уровне JSON-RPC, четыре топологии агентов поверх него и частота отказов каждой, измеренная в контролируемой модели сбоев. Мозг агента — детерминированная симуляция, а не живая LLM — скриптовая политика выполняет планы над реальным MCP-сервером, а параметризованный процесс сбоев возмущает её выбор с заданными частотами. Это инструмент, а не компромисс: частота отказов топологии, измеренная против живой модели, смешивается с недетерминизмом этой модели, и вы не можете сказать, вызвана ли разница топологией или сэмплером. Всё ниже — частота отказов топологии в модели сбоев, никогда не реальной модели.

Этот репозиторий отвечает на один вопрос:

Какова частота отказов каждой топологии агента, и действительно ли supervisor лучше, чем single-agent?

Ответ

Supervisor превосходит single-agent, но это стоит дороже, чем выигрыш, и его превосходят две более простые конструкции.

топология

частота отказов

токенов/запуск

против single

шаги

передачи

single

31.7%

2,449

1.00x

5.44

0.00

supervisor

28.2%

4,238

1.73x

5.16

3.88

pipeline

21.2%

3,244

1.32x

5.37

1.66

reflexive

4.5%

2,996

1.22x

6.31

0.32

600 запусков на топологию (6 задач x 100 испытаний), каждая топология сталкивается с идентичным потоком сбоев для данного (задача, испытание) — парное сравнение, а не четыре независимых выборки.

  • Выигрыш supervisor в 3.5 пункта — реален, не шум: парный бустрап-дельт -0.035 [-0.062, -0.008] при 95%, интервал исключает ноль.

  • Это стоит 1.73x токенов. pipeline и reflexive оба превосходят его по частоте отказов и по токенам. Платить 1.7x за третий по качеству результат — вот вывод.

  • Ранжирование reflexive < pipeline < supervisor < single сохраняется при развёртке частот сбоев от 0.5x до 2.0x.

  • Разрывы сужаются с ростом сбоев. Топология — эффект второго порядка; надёжность инструментов — первого порядка.

Полная таблица, доверительные интервалы и развёртка чувствительности: results/topologies.md. Каждое число генерируется скриптом scripts/generate_results.py, который утверждает свои собственные заявления и завершается с ненулевым кодом, если они нарушаются.

Related MCP server: agentloop

Более полезный ответ

При смешанной модели сбоев выше топологии выглядят похоже. Включайте один сбой за раз — и они радикально различаются — и какая топология помогает, полностью зависит от того, какой сбой у вас:

режим отказа

лучший

худший

решает ли топология?

Бесконечный цикл

supervisor 0.0%

single 24.6%

Да — пошаговые лимиты на единицу работы

Неверный выбор инструмента

reflexive 15.0%

pipeline 44.2%

Нет — исправьте схемы

Каскад ошибок

reflexive 21.7%

pipeline 56.7%

Нет — исправьте сообщения об ошибках

Истощение контекста

supervisor 0.0%

single 83.8%

Да — свежие контексты

Частичный сбой

—

—

Нет — журналируйте и компенсируйте

Неподтверждённое уничтожение

—

—

Нет — ограничьте инструмент

Два из шести исправляются топологией, оба одним и тем же свойством — изоляцией ресурсов на единицу работы, а не надзором как таковым. Остальные четыре исправляются на уровне инструментов. Обратите внимание, что supervisor и pipeline хуже, чем single, при каскадах ошибок: свежий контекст рабочего отбрасывает историю ошибок, которая могла бы подсказать, что не следует повторять вызов. Изоляция сдерживает каскады, но и ампутирует обучение.

Артефакт суждения с воспроизводимыми зернами, реальными трассировками и смягчающими мерами для каждого режима: docs/failure-taxonomy.md.

Область применения

Преднамеренно узкая. В области: поверхность протокола MCP, четыре топологии, шесть режимов отказов и стоимость токенов для каждой. Вне области: всё, что не помогает ответить на вопрос выше.

Краткое начало

uv sync --extra dev
uv run pytest -q                          # 90 tests
uv run python scripts/generate_results.py # regenerates results/
uv run python scripts/find_failure_seeds.py

Запустите MCP-сервер с любым клиентом, говорящим на stdio:

uv run python -m mcp_server_and_agent.server

Что здесь находится

файл

что это

src/.../protocol.py

Обрамление JSON-RPC 2.0, объекты ошибок, валидация запросов

src/.../server.py

Жизненный цикл MCP, диспетчеризация, дедупликация идемпотентности, цикл stdio

src/.../tools.py

5 инструментов, 1 ресурс, 1 промпт, шлюз подтверждения, журнал отката

src/.../faults.py

модель сбоев — независимая переменная эксперимента

src/.../agent.py

скриптовая политика, цикл ReAct, набор задач

src/.../topologies.py

четыре топологии

MCP-сервер написан по спецификации, а не на SDK

initialize / tools/list / tools/call / resources/read / prompts/get / ping с корректными объектами ошибок -32700 / -32600 / -32601 / -32602 / -32603. Причина не в чистоте: SDK скрывает именно те швы, которые измеряет этот репозиторий. Соответствие протоколу — одна из немногих вещей в стеке агента, которая точно тестируема — некорректный запрос имеет один правильный код ошибки — поэтому tests/test_protocol_conformance.py покрывает случаи, которые счастливая реализация делает неправильно: уведомления без ответа, "id": null как запрос, а не уведомление, отклонение пакета и границу ниже.

Инструмент, который не существует, — это -32602. Инструмент, который существует и даёт сбой, — это успешный ответ с isError. Первое — ошибка клиента; второе — обратная связь, на которую агент может действовать. Сведение их вместе означает, что агент либо бесконечно повторяет неисправимые вызовы, либо сдаётся на исправимых.

Четыре топологии

  • single — один агент, весь список инструментов, весь план. Базовый.

  • supervisor — супервизор отправляет каждый шаг новому рабочему. Каждая отправка платит налог за передачу, потому что рабочий начинает с холодного состояния.

  • pipeline — фиксированная цепочка discover → fetch → aggregate. Нет решения о маршрутизации, которое можно ошибить; нет повторного планировщика при сбое этапа. Контекстные потоки идут вперёд.

  • reflexive — один агент плюс ровно один проход размышления и повторной попытки. Выбран четвёртым, потому что изолирует то, что смешивает supervisor: стоит ли вторая попытка больше, чем второй агент. Обе стоят дополнительных токенов; в этой модели сбоев только одна добавляет способность.

Происхождение

Каждое число в этом README получено из закоммиченного скрипта.

  • Дата: 2026-08-25

  • Оборудование: 24-ядерный CPU, 32 ГБ ОЗУ, без GPU

  • Модель: simulated-scripted-policy — без LLM

  • Зерно: 20260825

  • Воспроизведение: python scripts/generate_results.py

  • Сырой артефакт: results/topologies-raw.md (в gitignore — детали по задачам)

  • Закоммиченный артефакт: results/topologies.md

CI перегенерирует results/ и падает на git diff --exit-code, поэтому вручную отредактированное число ломает сборку. Этот шлюз имеет смысл только потому, что эксперимент детерминирован — то же зерно, те же частоты сбоев — что tests/test_topologies.py утверждает в обоих направлениях.

Ограничения

  • Никакая LLM не участвовала в измерениях. Мозг агента — скриптовая политика, а сбои взяты из распределения, которое я выбрал. Это частоты отказов топологий в контролируемой модели сбоев, не любой реальной модели в любом реальном развёртывании. Переносится форма результата — какое смягчение атакует какой механизм, — а не значения.

  • Частоты сбоев не откалиброваны. Ничто здесь не устанавливает, что реальный агент неверно выбирает инструмент в 16% случаев. Их калибровка требует живых запусков, которые этот репозиторий намеренно не делает, и пока кто-то этого не сделает, абсолютные частоты произвольны и значимы только сравнения.

  • Подсчёты токенов синтетические: фиксированная плата за шаг плюс len(text)//4 за наблюдения. Согласовано между топологиями, чтобы соотношения держались; долларовые цифры не прогнозируют ничей счёт.

  • Шесть задач, один сервер, одна форма задач. Все шесть — поиск-затем-извлечение-затем-агрегация. Случай, который supervisor должен выигрывать — действительно параллельные, разделяемые подзадачи — здесь не представлен, и эти числа не являются доказательством против него. Это самое большое, чего репозиторий не устанавливает.

  • reflexive получает одну повторную попытку, которую другие не получают. Часть его преимущества — второй шанс из распределения сбоев, а не рефлексия как таковая.

  • Нет LangGraph. Бриф упомянул его; цикл агента здесь написан вручную в ~200 строках, потому что исследуемые режимы отказов являются свойствами цикла, и фреймворк сделал бы лимит шагов, учёт контекста и детектор каскадов чьими-то чужими деталями реализации.

  • Обнаружение измеряется, восстановление в основном нет. Помимо пути отката, это устанавливает, что отказы выявляются, а не что система, построенная на этих смягчениях, завершает больше задач.

Построено на

  • llm-client-kit v0.1.0 — CostLedger для учёта токенов и расходов.

  • llm-eval-harness v0.1.0 — stats.paired_delta_ci и is_reportable для доверительных интервалов, types.RunMeta для блока происхождения.

Лицензия

MIT — см. LICENSE.

Available Tools

5 tools
append_noteB

Append a free-text note to the session note log.

NameRequiredDescriptionDefault
textYesnote body

TDQS

B3.3/5.0
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

Annotations already declare idempotentHint=false and destructiveHint=false, so safety is covered. The description adds only the fact it appends to a log but does not disclose side effects, permissions, or failure behavior. Given the annotations, the description contributes minimal value beyond the obvious write nature.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is a single, front-loaded sentence with no extraneous detail. It efficiently conveys the core action and object.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness3/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

For a simple tool with one parameter and no output schema, the description is minimally adequate. However, it does not mention typical usage scenarios, return behavior, or failure modes, which could be helpful for an agent deciding whether this tool fits a given task.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema coverage is 100% and the parameter 'text' is documented as 'note body'. The description's phrase 'free-text note' adds a slight nuance about the unstructured nature of the input, but does not materially extend the schema. Baseline 3 is appropriate.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description uses a specific verb ('Append') with a clear resource ('session note log') and describes the content ('free-text note'). It is easily distinguished from the sibling tools (search_records, fetch_record, summarise_amounts, delete_record) which perform different actions.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines2/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides no explicit guidance on when to use this tool versus alternatives. It does not mention any prerequisites, exclusions, or typical workflows where appending a note would be appropriate over other operations.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

delete_recordA
Destructive

Permanently delete a record. Destructive and gated: the first call returns a confirm_token describing what would be deleted, and the deletion only happens on a second call carrying that token.

NameRequiredDescriptionDefault
record_idYesexact record id to delete
confirm_tokenNotoken from the prior unconfirmed call

TDQS

A4.4/5.0
Behavior5/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

Annotations already mark the tool as destructive and non-idempotent, and the description adds substantial context: permanence, the two-step confirmation mechanism, and the token's role. This is exactly the behavioral detail an agent needs beyond the structured annotations.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

A single, tightly packed sentence that front-loads the destructive nature and then explains the gating protocol. There is no filler, and every clause carries essential behavioral information.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness4/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

For a destructive two-step tool with no output schema, the description covers the critical interaction flow and irreversibility. It stops short of specifying the shape of the token response or any post-deletion confirmation, but the essential calling protocol is fully conveyed.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

The input schema already provides 100% parameter coverage, describing record_id and confirm_token clearly. The description reinforces the confirm_token semantics but does not add new parameter-level detail beyond what the schema already contains.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

States the exact operation ('Permanently delete a record') with a clear resource and irreversible effect. The description also distinguishes this from the sibling read/summarize/append tools by emphasizing deletion and the confirmation gate.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines4/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description clearly communicates that deletion is not immediate: the first call generates a confirm_token and only a second call with that token actually deletes. It implicitly tells an agent to never expect deletion on the first call, though it does not explicitly enumerate when not to use the tool.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

fetch_recordA
Idempotent

Fetch one record by its exact id. Returns the record's title, owner, amount and tags.

NameRequiredDescriptionDefault
record_idYesexact record id, e.g. rec-001

TDQS

A4.3/5.0
Behavior4/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

Annotations already declare idempotentHint=true and destructiveHint=false, covering the safety profile. The description adds value by disclosing that the response includes title, owner, amount, and tags, which is beyond structured annotations and helps the agent set expectations for the returned data.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

A single, front-loaded sentence that states the operation and its result with no filler. Every word contributes meaning, and the structure is easy to parse quickly.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness5/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

For a simple one-parameter read operation, the description is complete: it names the input, explains the match criterion, and lists the returned fields. The output schema is absent, but the description explicitly fills that gap. Sibling distinctions are evident through the 'exact id' wording, and the annotations cover behavioral safety.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 100%, with record_id already documented as an exact record id with an example. The description merely reinforces the schema rather than adding new semantic detail. Baseline of 3 is appropriate because the schema carries the parameter meaning and the description adds minimal extra value.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

States a specific verb ('Fetch'), a resource ('one record'), and the lookup key ('exact id'), which clearly differentiates it from the sibling search_records. The added return-field list further clarifies the tool's scope. This is a precise, unambiguous definition.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines4/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The phrase 'by its exact id' implies the proper context: when the caller already knows the precise identifier. It does not explicitly name alternatives like search_records for fuzzy or filtered lookup, but the context is clear enough for an agent to select this tool over the siblings.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

search_recordsA
Idempotent

Search the record store by a free-text query matched against title, owner and tags. Returns matching record ids.

NameRequiredDescriptionDefault
queryYesfree-text search term

TDQS

A4.4/5.0
Behavior4/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

Annotations already indicate idempotent and non-destructive behavior. The description adds useful behavioral detail: it specifies what fields are matched, that the query is free-text, and that the result is a set of record ids. This is meaningful context beyond the annotations, especially since there is no output schema.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is two short sentences with no redundant wording. The action and scope are front-loaded, and every phrase contributes useful information.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness4/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

For a single-parameter, non-destructive search tool with idempotency annotations, the description covers the core behavior and return value sufficiently. Minor details like pagination, ordering, or empty-result behavior are absent, but they are not essential for correct invocation.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters4/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

The schema fully documents the query parameter as a 'free-text search term'. The description adds semantic value by explaining that the term is matched against title, owner, and tags, which clarifies how the parameter is interpreted beyond the schema alone.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description uses a specific verb ('Search') and resource ('record store'), and further clarifies the scope by naming the matched fields (title, owner, tags) and the output (matching record ids). This clearly distinguishes search_records from siblings like fetch_record and delete_record, which imply direct record retrieval or mutation.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines4/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description makes clear this tool is for free-text, field-matching search across records. It gives enough context for an agent to select it for search-style queries, though it does not explicitly contrast it with fetch_record or other alternatives.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

summarise_amountsA
Idempotent

Compute count, total and mean of the amount field across the given record ids. All ids must exist.

NameRequiredDescriptionDefault
record_idsYeslist of exact record ids

TDQS

A4.1/5.0
Behavior4/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

The annotations already declare idempotentHint=true and destructiveHint=false, and the description does not contradict them. It adds meaningful behavioral context beyond annotations by stating the precondition that all ids must exist and by naming the calculated summary values, which is especially valuable because no output schema is provided.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is two concise sentences with no filler: the first states the operation and its outputs, and the second states the single relevant precondition. The key information is front-loaded and easy for an agent to parse quickly.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness5/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

For a simple one-parameter, non-destructive, idempotent aggregation tool, the description is complete: it states what is computed, over which input, and the required precondition. Although there is no output schema, naming count, total, and mean sufficiently describes the return values.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema coverage is 100% because the input schema already describes record_ids as 'list of exact record ids'. The description adds the role of the ids in the aggregation and mentions the 'amount field', but it does not provide deeper parameter-level detail, so the baseline score of 3 is appropriate.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description uses a specific verb ('Compute') and identifies the resource ('amount field') and the scope ('given record ids'), clearly distinguishing this as an aggregation tool from the sibling fetch/search/mutation tools. It also enumerates the three outputs (count, total, mean), leaving no ambiguity about what the tool returns.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines3/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

Usage is implied: an agent can infer this tool is for summarizing amounts across a known set of record ids, and the precondition 'All ids must exist' adds a useful constraint. However, it does not explicitly contrast with alternatives like search_records or fetch_record, nor state when this tool should be preferred over them.

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.

  1. 5 tool updatesv0.1.0
    • First observedappend_note
    • First observeddelete_record
    • First observedfetch_record
    • First observedsearch_records
    • First observedsummarise_amounts

TDQS

A4/5.0

Scored across 5 tools

Disambiguation5/5

Each tool performs a distinct action: searching, fetching by ID, aggregating amounts, appending notes, and deleting records. There is no overlap or ambiguity between them.

Naming Consistency5/5

All tool names consistently follow the verb_noun pattern (search_records, fetch_record, summarise_amounts, append_note, delete_record), using uniform snake_case naming.

Tool Count5/5

With 5 tools, the surface is well-scoped and covers essential operations without bloat or unnecessary duplication. The count is appropriate for a focused record management server.

Completeness3/5

The tools cover search, fetch, aggregation, note appending, and deletion, but lack create and update operations. While the server may be intentionally read-only plus deletion, the asymmetry is a notable gap for a record management domain.

Maintenance

ActivitySlowing
ResponsivenessNo issues

Related MCP Connectors

Related MCP Servers