Skip to main content
Glama

MandatePay

Межсетевой экран авторизации для агентных платежей

Идентичность · Намерение · Политика · Одобрение человеком · Криптографическое доказательство

CI Python MCP License

Автономные агенты могут предлагать платежи. Они не должны получать неограниченные финансовые полномочия. MandatePay проверяет каждый инициированный машиной платёж на соответствие подписанному человеком мандату до его исполнения.

Зачем это существует

Агентная коммерция порождает новую проблему контроля: как платёжный провайдер может доказать, что ИИ-агент действовал в рамках полномочий, делегированных человеком или организацией? Традиционный checkout предполагает присутствие человека. API-ключи устанавливают доступ к приложению, но не цель, лимиты, географию, круг мерчантов или точные границы делегированного намерения.

MandatePay — это исследовательская плоскость управления, которая располагается между агентами и платёжными рельсами. Она не хранит и не перемещает средства.

Related MCP server: Safe4

Что делает её особенной

  • Подписанные мандаты: полномочия проверяемы машиной и защищены от подделки.

  • Политика как код: детерминированные лимиты на сумму, общий объём расходов, валюту, страну, мерчанта, цель, срок действия и скорость.

  • Человеческий вызов: операции с более высоким риском приостанавливаются для одобрения, привязанного к конкретному платежу.

  • Привязка к идентичности агента: мандат не может быть использован другим агентом.

  • Защита от повторов: ключи идемпотентности возвращают исходное решение.

  • Проверяемые события: каждое решение попадает в журнал с хеш-цепочкой.

  • MCP-инструмент: агенты могут запрашивать авторизацию через ограниченный интерфейс инструмента.

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

Жизненный цикл авторизации

sequenceDiagram
    participant H as Human / Organization
    participant A as AI Agent
    participant M as MandatePay
    participant P as Payment Provider
    H->>M: Sign bounded mandate
    A->>M: Submit payment intent
    M->>M: Verify identity + signature + policy + state
    alt within authority
        M-->>A: Single-use authorization
        A->>P: Execute with authorization proof
    else approval threshold
        M-->>H: Challenge exact intent
    else policy violation
        M-->>A: Deny with reason codes
    end
    M->>M: Append decision to audit chain

Быстрый старт

git clone https://github.com/muhammadashir0/mandatepay.git
cd mandatepay
python -m unittest discover -s tests -v
python app.py

Откройте http://localhost:8080.

Попробуйте четыре сценария в консоли:

  1. €299 / software / DE → авторизовать

  2. €400 / software / DE → человеческий вызов

  3. €900 / software / DE → отклонить: превышение лимита платежа

  4. €100 / travel / GB → отклонить: цель и страна

Используйте новый ключ идемпотентности при смене сценария.

MCP-сервер

python -m mandatepay.mcp_server

JSON-RPC-сервер без зависимостей предоставляет один намеренно узкий инструмент: request_payment_authorization. Инструмент возвращает решение, а не движение денежных средств.

Модель угроз

MandatePay разработан с учётом:

  • украденных или избыточно привилегированных учётных данных агента;

  • prompt-инъекций, вызывающих непреднамеренные покупки;

  • подделки мандатов и эскалации области действия;

  • дублирующего исполнения и повторов;

  • злоупотребления скоростью и совокупного перерасхода;

  • неоднозначного одобрения человеком;

  • неполных судебно-медицинских доказательств.

См. docs/THREAT_MODEL.md о границах доверия, нецелях и производственных средствах контроля.

Архитектура репозитория

mandatepay/
├── mandatepay/
│   ├── core.py          # signed mandate + deterministic policy engine
│   ├── store.py         # state, idempotency, tamper-evident journal
│   └── mcp_server.py    # constrained MCP-compatible tool server
├── web/index.html       # premium operator console
├── tests/               # policy and adversarial scenarios
├── docs/                # protocol, threat model, product direction
└── app.py               # sandbox HTTP API

Оценка, а не просто демонстрация

Тесты проверяют авторизацию, вызовы на одобрение, несовпадение идентичности, выход за рамки области действия, лимиты скорости и подделку подписанных мандатов. Следующий уровень бенчмарков будет измерять ложные авторизации, ложные отказы, устойчивость к повторам, покрытие политик, задержку решений и нагрузку на одобрение в состязательных сценариях.

Дорожная карта

  • Продакшн-подпись Ed25519/JWS и ротация ключей

  • Удостоверенная через OAuth идентичность агента и workload identity

  • Церемония одобрения, привязанная к хешу намерения

  • Одноразовые токены авторизации для платёжных провайдеров

  • Долговечный SQL-журнал с гарантиями конкурентности

  • OpenTelemetry-трассировки решений и экспорт подписанного аудита

  • Состязательный оценочный корпус для атак на агентные платежи

  • Песочница-адаптер Stripe/Adyen за интерфейсом исполнения

  • Мультивалютные десятичные и FX-политики

Границы ответственного использования

Этот репозиторий — исследовательский MVP в области безопасности и FinTech, использующий синтетические идентичности и не оперирующий реальными средствами. HMAC используется только для того, чтобы демонстрация оставалась без зависимостей. Для продакшн-развёртывания требуются проверенная асимметричная криптография, усиленная идентичность, долговечное транзакционное хранилище, аутентификация и авторизация, регуляторный анализ, средства контроля конфиденциальности, независимое тестирование безопасности и сертификация платёжного провайдера.

Стратегический контекст

Агентным платёжным системам необходимы авторизация на основе мандатов, разделение решения и исполнения, идентичность агента, программируемые средства контроля, аудиторские следы и многоуровневый человеческий надзор. MandatePay превращает эти проектные требования в инспектируемый прототип с открытым исходным кодом.

Лицензия

Apache License 2.0.

Available Tools

1 tool
request_payment_authorizationA

Evaluate a proposed agent payment against a signed spending mandate. Does not move funds.

NameRequiredDescriptionDefault
amountYes
purposeYes
currencyYes
merchant_idYes
merchant_countryYes

TDQS

A3.9/5.0
Behavior4/5

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

With no annotations provided, the description carries the burden of behavioral disclosure. The explicit statement 'Does not move funds' is a critical side-effect disclosure that prevents accidental fund transfers. However, it does not describe the output nature (e.g., approval/denial) or any other side effects, leaving some behavioral gaps. The core non-effect is well covered, so a 4 is appropriate.

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, leading with the core purpose and then a critical safety note. There is no wasted wording, and the most important information (the scrutiny and non-movement) is front-loaded. This is an exemplary level of conciseness.

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

Completeness2/5

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

The description is too brief for a tool with five required parameters and no output schema. It omits the return value (e.g., whether the authorization is granted or denied), any prerequisites like having the mandate document, and does not clarify the 'purpose' field's semantics. An agent lacks critical information to interpret the tool's result and handle errors effectively, making it incomplete.

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

Parameters2/5

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

The schema description coverage is 0%, so the description must compensate by explaining the parameters. It does not describe any of the five fields (amount, currency, merchant_id, merchant_country, purpose). The context of a 'proposed agent payment' hints at their role but provides no additional meaning beyond the schema's field names, which is insufficient for a tool with no inline descriptions.

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 ('Evaluate') and a clear resource ('proposed agent payment against a signed spending mandate'), and explicitly states it does not move funds, which distinguishes it from payment execution tools. Even without siblings, the purpose is precise and unambiguous, leaving no doubt about what the tool does.

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 implies the use case: evaluating a payment proposal against a mandate before funds are moved. It does not explicitly state when not to use it or mention alternatives, but the context is strong enough that an agent understands when to invoke it. Since no siblings are present, the lack of exclusions is acceptable.

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. 1 tool updatev0.1.0
    • First observedrequest_payment_authorization

TDQS

A3.9/5.0

Scored across 1 tool

Disambiguation5/5

With only one tool, there is no possibility of confusion or overlap between tools. The tool's purpose is clearly defined and singular.

Naming Consistency5/5

A single tool follows a consistent verb_noun pattern ('request_payment_authorization'), which is clear and descriptive. No inconsistencies exist by definition.

Tool Count3/5

The server has only one tool, which feels thin for a system named 'MandatePay'—implying broader mandate management. While the tool itself is well-scoped, the overall surface is borderline minimal.

Completeness2/5

The tool covers only payment authorization, but the domain suggests the need for related operations like mandate creation, listing, updating, or checking status. Without these, agents face significant dead ends when managing mandates.

Maintenance

ActivityStale
ResponsivenessNo issues

Related MCP Connectors

Related MCP Servers

  • A
    license
    Not graded
    quality
    C
    maintenance
    Enables AI agents to verify proposed payments against their assigned task, budgets, permitted categories, and counterparties, returning an ALLOW or DENY decision with a tamper-evident audit trail.
    MIT
  • A
    license
    Not graded
    quality
    B
    maintenance
    Enables AI agents to use payment APIs safely by gating every tool call through deterministic mandates, value checks, and an exactly-once ledger, so they cannot pay twice or exceed authorisation.
    81 npm
    MIT
  • A
    license
    Not graded
    quality
    F
    maintenance
    Enables MCP clients to ask permission before an agent acts, returning allow, deny, or ask_human with receipts, and to monitor agent spend, limits, and recent decisions.
    0
    Functional Source , Version 1.1, ALv2 Future