> ## Documentation Index
> Fetch the complete documentation index at: https://docs.mnemom.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# SDK Direct Integration

> Integrate alignment verification, integrity checking, and policy governance directly into your application

Use the AAP and AIP SDKs to add alignment verification and integrity checking directly to your application code. This gives you full control over when traces are generated, how integrity checks run, and what happens on violations. For governance features (policy enforcement, violation reclassification, trust recovery), use the [Policy API](/api-reference/policy-overview) and [Reclassification API](/api-reference/reclassification-overview) alongside the SDKs.

<Note>
  These quickstarts are available in [Spanish (Español)](/es/quickstart/overview) and [French (Français)](/fr/quickstart/overview) — six pages per language have been translated.
</Note>

## Install

<CodeGroup>
  ```bash Python theme={null}
  pip install agent-alignment-protocol agent-integrity-proto
  ```

  ```bash TypeScript theme={null}
  npm install --legacy-peer-deps @mnemom/agent-alignment-protocol @mnemom/agent-integrity-protocol
  ```
</CodeGroup>

<Note>
  `--legacy-peer-deps` is needed on npm 7+ while `@mnemom/agent-integrity-protocol` 1.3.0 still declares an optional peer on the 1.x alignment-protocol package; the two SDKs work together at 2.0.0 / 1.3.0.
</Note>

<Steps>
  <Step title="Define an Alignment Card">
    An Alignment Card declares your agent's identity, values, autonomy boundaries, and audit commitments. Every trace and integrity check is verified against this card.

    <CodeGroup>
      ```python Python theme={null}
      from aap import AlignmentCard, Principal, Values, Autonomy, Audit

      card = AlignmentCard(
          card_version="unified/2026-04-26",
          card_id="ac-my-agent-001",
          agent_id="my-agent",
          issued_at="2026-01-31T12:00:00Z",
          autonomy_mode="observe",
          integrity_mode="observe",

          principal=Principal(
              type="human",
              identifier="did:web:user.example.com",
              relationship="delegated_authority",
          ),

          values=Values(
              declared=["principal_benefit", "transparency", "minimal_data"],
              conflicts_with=["deceptive_marketing", "hidden_fees"],
          ),

          autonomy=Autonomy(
              bounded_actions=["search", "compare", "recommend", "add_to_cart"],
              escalation_triggers=[
                  {"condition": "action_type == \"purchase\"", "action": "escalate",
                   "reason": "Purchases require approval"},
                  {"condition": "purchase_value > 100", "action": "escalate",
                   "reason": "Exceeds spending limit"},
              ],
              forbidden_actions=["share_credentials", "subscribe_to_services"],
          ),

          audit=Audit(
              trace_format="ap-trace-v1",
              retention_days=90,
              queryable=True,
              query_endpoint="https://my-agent.example.com/api/v1/traces",
          ),
      )

      card_dict = card.model_dump()
      ```

      ```typescript TypeScript theme={null}
      import type { AlignmentCard } from '@mnemom/agent-alignment-protocol';

      const card: AlignmentCard = {
        card_version: 'unified/2026-04-26',
        card_id: 'ac-my-agent-001',
        agent_id: 'my-agent',
        issued_at: '2026-01-31T12:00:00Z',
        autonomy_mode: 'observe',
        integrity_mode: 'observe',

        principal: {
          type: 'human',
          identifier: 'did:web:user.example.com',
          relationship: 'delegated_authority',
        },

        values: {
          declared: ['principal_benefit', 'transparency', 'minimal_data'],
          conflicts_with: ['deceptive_marketing', 'hidden_fees'],
        },

        autonomy: {
          bounded_actions: ['search', 'compare', 'recommend', 'add_to_cart'],
          escalation_triggers: [
            { condition: 'action_type == "purchase"', action: 'escalate',
              reason: 'Purchases require approval' },
            { condition: 'purchase_value > 100', action: 'escalate',
              reason: 'Exceeds spending limit' },
          ],
          forbidden_actions: ['share_credentials', 'subscribe_to_services'],
        },

        audit: {
          trace_format: 'ap-trace-v1',
          retention_days: 90,
          queryable: true,
          query_endpoint: 'https://my-agent.example.com/api/v1/traces',
        },
      };
      ```
    </CodeGroup>

    <Note>
      **Field names changed in the unified card shape (AAP 2.0.0).** `aap_version` is now `card_version` (date-anchored); `autonomy_envelope`/`AutonomyEnvelope` is now `autonomy`/`Autonomy`; `audit_commitment`/`AuditCommitment` is now `audit`/`Audit`; `autonomy_mode` and `integrity_mode` are new top-level fields; `principal.identifier` is required whenever `principal.type` isn't `unspecified`; and `audit.queryable: true` requires `audit.query_endpoint`. See [migrating from the legacy 0.5.0 card shape](/protocols/aap/specification#410-migrating-from-the-legacy-050-card-shape) for the full mapping.
    </Note>

    <Tip>
      The Alignment Card is the foundation of both protocols. Define it once and use it for AAP verification, AIP integrity checking, and value coherence checks.
    </Tip>
  </Step>

  <Step title="Generate AP-Traces from agent actions">
    Every significant decision your agent makes should produce an AP-Trace. The trace records the action taken, alternatives considered, reasoning applied, and whether escalation was evaluated.

    <CodeGroup>
      ```python Python theme={null}
      from aap import APTrace, Action, Decision, Alternative, Escalation
      from datetime import datetime
      import uuid

      trace = APTrace(
          trace_id=f"tr-{uuid.uuid4().hex[:12]}",
          agent_id="my-agent",
          card_id="ac-my-agent-001",
          timestamp=datetime.utcnow().isoformat() + "Z",

          action=Action(
              type="recommend",
              name="recommend",
              category="bounded",
          ),

          decision=Decision(
              alternatives_considered=[
                  Alternative(option_id="prod-A", description="Widget Pro",
                             score=0.9, scoring_factors={"relevance": 0.95, "value": 0.85}),
                  Alternative(option_id="prod-B", description="Widget Basic",
                             score=0.7, scoring_factors={"relevance": 0.80, "value": 0.60}),
                  Alternative(option_id="prod-C", description="Sponsored Widget",
                             score=0.5, scoring_factors={"relevance": 0.50, "value": 0.40},
                             flags=["sponsored_content"]),
              ],
              selected="prod-A",
              selection_reasoning="Highest preference match. Sponsored options deprioritized per principal_benefit value.",
              values_applied=["principal_benefit", "transparency"],
              confidence=0.9,
          ),

          escalation=Escalation(
              evaluated=True,
              triggers_checked=[
                  {"trigger": "action_type == \"purchase\"", "matched": False},
              ],
              required=False,
              reason="Recommendation only, no purchase action",
          ),
      )

      trace_dict = trace.model_dump()
      ```

      ```typescript TypeScript theme={null}
      import type { APTrace } from '@mnemom/agent-alignment-protocol';

      const trace: APTrace = {
        trace_id: `tr-${crypto.randomUUID().slice(0, 12)}`,
        agent_id: 'my-agent',
        card_id: 'ac-my-agent-001',
        timestamp: new Date().toISOString(),

        action: {
          type: 'recommend',
          name: 'recommend',
          category: 'bounded',
        },

        decision: {
          alternatives_considered: [
            { option_id: 'prod-A', description: 'Widget Pro',
              score: 0.9, scoring_factors: { relevance: 0.95, value: 0.85 } },
            { option_id: 'prod-B', description: 'Widget Basic',
              score: 0.7, scoring_factors: { relevance: 0.80, value: 0.60 } },
            { option_id: 'prod-C', description: 'Sponsored Widget',
              score: 0.5, scoring_factors: { relevance: 0.50, value: 0.40 },
              flags: ['sponsored_content'] },
          ],
          selected: 'prod-A',
          selection_reasoning:
            'Highest preference match. Sponsored options deprioritized per principal_benefit value.',
          values_applied: ['principal_benefit', 'transparency'],
          confidence: 0.9,
        },

        escalation: {
          evaluated: true,
          triggers_checked: [
            { trigger: 'action_type == "purchase"', matched: false },
          ],
          required: false,
          reason: 'Recommendation only, no purchase action',
        },
      };
      ```
    </CodeGroup>

    <Tip>
      Verification matches `action.name` against `bounded_actions`, not `action.type`. Both fields serve different purposes: `type` is a semantic category; `name` is the specific operation identifier checked against the card's `bounded_actions` list.
    </Tip>
  </Step>

  <Step title="Verify traces against the card">
    Verification checks whether the agent's behavior (recorded in the trace) is consistent with its declared alignment (the card). It returns structural checks, a similarity score, and any violations or warnings.

    <CodeGroup>
      ```python Python theme={null}
      from aap import verify_trace

      result = verify_trace(trace_dict, card_dict)

      print(f"Verified: {result.verified}")
      print(f"Similarity: {result.similarity_score:.2f}")

      if not result.verified:
          for violation in result.violations:
              print(f"VIOLATION [{violation.severity}]: {violation.type}")
              print(f"  {violation.description}")

      for warning in result.warnings:
          print(f"WARNING: {warning.type}")
          print(f"  {warning.description}")

      # Example output for a compliant trace:
      # Verified: True
      # Similarity: 0.82

      # Example output for a violation:
      # Verified: False
      # Similarity: 0.15
      # VIOLATION [HIGH]: unbounded_action
      #   Action 'delete_account' not in bounded_actions
      ```

      ```typescript TypeScript theme={null}
      import { verifyTrace } from '@mnemom/agent-alignment-protocol';

      const result = verifyTrace(trace, card);

      console.log(`Verified: ${result.verified}`);
      console.log(`Similarity: ${result.similarity_score.toFixed(2)}`);

      if (!result.verified) {
        for (const violation of result.violations) {
          console.log(`VIOLATION [${violation.severity}]: ${violation.type}`);
          console.log(`  ${violation.description}`);
        }
      }

      for (const warning of result.warnings) {
        console.log(`WARNING: ${warning.type}`);
        console.log(`  ${warning.description}`);
      }
      ```
    </CodeGroup>

    <Note>
      The `similarity_score` (0.0 to 1.0) measures how semantically similar the trace's behavior is to the declared alignment. A trace can pass all structural checks but still receive a `low_behavioral_similarity` warning if the score falls below 0.50. See [calibration](/protocols/aap/calibration) for how thresholds were derived.
    </Note>
  </Step>

  <Step title="Add integrity checkpoints">
    AIP integrity checking analyzes LLM thinking blocks per turn to detect prompt injection, value drift, and manipulation. Each check produces a verdict: `clear`, `review_needed`, or `boundary_violation`.

    <Warning>
      **AIP defaults to fail-open mode.** If the analysis LLM is unreachable, integrity checks will silently pass. For production deployments handling sensitive operations, set `failure_policy: { mode: "fail_closed" }` in your AIP configuration.
    </Warning>

    A client does the extraction, the LLM call, and the checkpoint/window bookkeeping for you — hand it the raw provider response body, not a pre-extracted thinking string. The `card` here is AIP's own minimal card shape (`card_id`, `values`, `autonomy_envelope`) — a small subset of fields, kept separate from the full AAP `AlignmentCard` you built in Step 1, since `@mnemom/agent-alignment-protocol` is only an optional peer dependency for AIP.

    <CodeGroup>
      ```python Python theme={null}
      from aip import create_client
      from aip.schemas.config import (
          AIPConfig, AnalysisLLMConfig, WindowConfig,
          AlignmentCard as AIPCard, AlignmentCardValue, AutonomyEnvelope,
      )

      client = create_client(AIPConfig(
          card=AIPCard(
              card_id="ac-my-agent-001",
              values=[AlignmentCardValue(name="principal_benefit", priority=1)],
              autonomy_envelope=AutonomyEnvelope(
                  bounded_actions=["search", "compare", "recommend", "add_to_cart"],
              ),
          ),
          analysis_llm=AnalysisLLMConfig(
              model="claude-haiku-4-5-20251001",
              base_url="https://api.anthropic.com",
              api_key="your-anthropic-api-key",
              max_tokens=1024,
          ),
          window=WindowConfig(),
          agent_id="my-agent",
      ))

      # response_body is the raw JSON text of the provider response your agent
      # just received (the one carrying the thinking block to be analyzed).
      signal = await client.check(response_body)

      print(f"Verdict: {signal.checkpoint.verdict}")   # "clear"
      print(f"Concerns: {signal.checkpoint.concerns}") # []
      print(f"Proceed: {signal.proceed}")              # True
      print(f"Action: {signal.recommended_action}")    # "continue"
      ```

      ```typescript TypeScript theme={null}
      import { createClient } from '@mnemom/agent-integrity-protocol';

      const client = createClient({
        card: {
          card_id: 'ac-my-agent-001',
          values: [{ name: 'principal_benefit', priority: 1 }],
          autonomy_envelope: {
            bounded_actions: ['search', 'compare', 'recommend', 'add_to_cart'],
          },
        },
        analysis_llm: {
          model: 'claude-haiku-4-5-20251001',
          base_url: 'https://api.anthropic.com',
          api_key: 'your-anthropic-api-key',
          max_tokens: 1024,
        },
        window: {},
        agent_id: 'my-agent',
      });

      // responseBody is the raw JSON text of the provider response your agent
      // just received (the one carrying the thinking block to be analyzed).
      const signal = await client.check(responseBody);

      console.log(`Verdict: ${signal.checkpoint.verdict}`);   // "clear"
      console.log(`Concerns: ${signal.checkpoint.concerns}`); // []
      console.log(`Proceed: ${signal.proceed}`);              // true
      console.log(`Action: ${signal.recommended_action}`);    // "continue"
      ```
    </CodeGroup>

    <Tip>
      `client.check()` runs the full pipeline every call: extract the thinking block for the detected provider, call the analysis LLM, parse the verdict, update the sliding window, and detect drift. There is no separate low-level "just parse this analysis response" function in the public API — `check()` is the one entry point.
    </Tip>

    ### Verdict to Action Mapping

    | Verdict | Proceed | Recommended Action |
    | - | - | - |
    | `clear` | Yes | `continue` |
    | `review_needed` | Yes | `log_and_continue` |
    | `boundary_violation` | No | `pause_for_review` or `deny_and_escalate` |
  </Step>

  <Step title="Check value coherence">
    Before your agent collaborates with another agent, verify their values are compatible. Coherence checking compares declared values and detects conflicts.

    <CodeGroup>
      ```python Python theme={null}
      from aap import check_coherence

      their_card = {
          "card_id": "ac-vendor-agent",
          "values": {
              "declared": ["customer_satisfaction", "transparency", "upselling"],
              "conflicts_with": ["price_comparison"],
          },
          # ... other fields
      }

      result = check_coherence(card_dict, their_card)

      print(f"Compatible: {result.compatible}")
      print(f"Coherence score: {result.score}")
      print(f"Matched values: {result.value_alignment.matched}")
      print(f"Conflicts: {[c.description for c in result.value_alignment.conflicts]}")

      if result.proceed:
          coordinate_with_agent(their_card)
      else:
          if result.proposed_resolution:
              print(f"Suggested resolution: {result.proposed_resolution}")
          escalate_to_principal(result.value_alignment.conflicts)

      # Example output:
      # Compatible: False
      # Coherence score: 0.4
      # Matched values: ['transparency']
      # Conflicts: ["Responder's 'upselling' may conflict with initiator's 'principal_benefit'"]
      ```

      ```typescript TypeScript theme={null}
      import { checkCoherence } from '@mnemom/agent-alignment-protocol';

      const theirCard = {
        card_id: 'ac-vendor-agent',
        values: {
          declared: ['customer_satisfaction', 'transparency', 'upselling'],
          conflicts_with: ['price_comparison'],
        },
        // ... other fields
      };

      const result = checkCoherence(card, theirCard);

      console.log(`Compatible: ${result.compatible}`);
      console.log(`Coherence score: ${result.score}`);
      console.log(`Matched values: ${result.value_alignment.matched}`);

      if (!result.proceed) {
        console.log('Conflicts:', result.value_alignment.conflicts
          .map(c => c.description));
      }
      ```
    </CodeGroup>
  </Step>
</Steps>

## Automatic tracing with decorators (Python)

The AAP Python SDK provides decorators for automatic trace generation:

```python theme={null}
from aap import trace_decision, TracedResult

@trace_decision(card_path="alignment-card.json")
def recommend_product(query: str) -> TracedResult:
    """Return TracedResult for detailed decision metadata."""
    products = find_products(query)
    best = products[0]

    return TracedResult(
        result=best,
        alternatives=[
            {"option_id": p["id"], "score": p["score"]}
            for p in products[:3]
        ],
        reasoning=f"Selected {best['name']} with highest score",
        values_applied=["principal_benefit", "transparency"],
        confidence=best["score"],
    )
```

## Drift detection

Monitor your agent for behavioral drift over time:

<CodeGroup>
  ```python Python theme={null}
  from aap import detect_drift

  traces = [trace1, trace2, trace3, ...]  # List of trace dicts

  alerts = detect_drift(traces=traces, card=card_dict)

  for alert in alerts:
      print(f"DRIFT DETECTED for agent {alert.agent_id}")
      print(f"  Direction: {alert.analysis.drift_direction}")
      print(f"  Similarity score: {alert.analysis.similarity_score}")
      print(f"  Sustained for {alert.analysis.sustained_traces} traces")
  ```

  ```typescript TypeScript theme={null}
  import { detectDrift } from '@mnemom/agent-alignment-protocol';

  const alerts = detectDrift(card, traces);

  for (const alert of alerts) {
    console.log(`DRIFT DETECTED for agent ${alert.agent_id}`);
    console.log(`  Direction: ${alert.analysis.drift_direction}`);
    console.log(`  Similarity: ${alert.analysis.similarity_score}`);
    console.log(`  Sustained for ${alert.analysis.sustained_traces} traces`);
  }
  ```
</CodeGroup>

## Next steps

* [CLPI overview](/concepts/clpi) -- Governance layer: policy enforcement, trust recovery, on-chain anchoring
* [Policy API](/api-reference/policy-overview) -- Programmatic policy management for SDK integrations
* [Reclassification API](/api-reference/reclassification-overview) -- Violation reclassification and trust score recovery
* [AAP specification](/protocols/aap/specification) -- Full protocol details for implementers
* [AIP specification](/protocols/aip/specification) -- Integrity protocol details
* [Limitations](/protocols/aap/limitations) -- What AAP can and cannot guarantee
* [Security model](/protocols/aap/security) -- Threat model and attack surfaces
* [A2A integration](/protocols/aap/a2a-integration) -- Adding AAP to A2A agent workflows
* [MCP migration](/protocols/aap/mcp-migration) -- Adding alignment tracing to MCP tools


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.