decision_add_context

Adds a context event to the decision trace. Use this to store important additional context from the agent that should be part of the decision audit trail.

Overview

The decision_add_context method allows you to add custom context events to a decision trace. These events become part of the immutable audit log and can include agent reasoning, intermediate decisions, confidence scores, model metadata, or any other contextual information relevant to the decision.

Request

Parameters

ParameterTypeRequiredDescription
decision_idstringYesThe decision ID (from decision_create)
contextobjectYesContext data to store (any JSON object)
summarystringNoHuman-readable summary of the context

Example Request

json
{
  "jsonrpc": "2.0",
  "id": 1,
  "method": "tools/call",
  "params": {
    "name": "decision_add_context",
    "arguments": {
      "decision_id": "TMEM_abc123...",
      "context": {
        "reasoning": "Customer has excellent payment history",
        "risk_score": 0.12,
        "confidence": 0.95,
        "model_version": "v2.3.1",
        "selected_option": "approve_discount"
      },
      "summary": "LLM risk assessment for discount decision"
    }
  }
}

Response

Success Response

json
{
  "jsonrpc": "2.0",
  "id": 1,
  "result": {
    "content": [
      {
        "type": "text",
        "text": "{\"event_id\": \"evt_...\", \"timestamp\": \"2026-01-07T12:03:00Z\"}"
      }
    ]
  }
}

Response Fields

FieldTypeDescription
event_idstringUnique identifier for this context event
timestampstringISO 8601 timestamp when the context was added

Example Response

json
{
  "event_id": "evt_context_abc123",
  "timestamp": "2026-01-07T12:03:00Z"
}

Error Cases

Missing Required Parameters

Error Code: -32600 (Invalid Request)

json
{
  "jsonrpc": "2.0",
  "id": 1,
  "error": {
    "code": -32600,
    "message": "Invalid Request",
    "data": "decision_id is required"
  }
}

Empty Context

Error Code: -32600 (Invalid Request)

json
{
  "jsonrpc": "2.0",
  "id": 1,
  "error": {
    "code": -32600,
    "message": "Invalid Request",
    "data": "context is required and must not be empty"
  }
}

Decision Not Found

Error Code: -32603 (Internal error)

json
{
  "jsonrpc": "2.0",
  "id": 1,
  "error": {
    "code": -32603,
    "message": "Internal error",
    "data": "Decision not found"
  }
}

Decision Already Closed

Error Code: -32603 (Internal error)

json
{
  "jsonrpc": "2.0",
  "id": 1,
  "error": {
    "code": -32603,
    "message": "Internal error",
    "data": "Cannot add context to closed decision"
  }
}

Authentication Errors

HTTP Status: 401 Unauthorized

Occurs when:

  • API key is missing
  • API key is invalid
  • API key has been revoked

Usage Examples

Add Agent Reasoning

python
import requests
import json

def add_context(decision_id, context, summary=None, api_key=None):
    args = {
        "decision_id": decision_id,
        "context": context
    }
    if summary:
        args["summary"] = summary
    
    response = requests.post('https://mcp.tracemem.com',
        headers={'Authorization': f'Agent {api_key}'},
        json={
            "jsonrpc": "2.0",
            "id": 1,
            "method": "tools/call",
            "params": {
                "name": "decision_add_context",
                "arguments": args
            }
        })
    
    result = response.json()
    if "error" in result:
        raise Exception(result["error"]["data"])
    
    context_data = json.loads(result["result"]["content"][0]["text"])
    return context_data

# Add reasoning context
add_context(
    decision_id="TMEM_abc123...",
    context={
        "reasoning": "Customer has excellent payment history",
        "risk_score": 0.12,
        "confidence": 0.95
    },
    summary="LLM risk assessment",
    api_key="YOUR_API_KEY"
)

Store Model Metadata

python
# Add model version and configuration
add_context(
    decision_id=decision_id,
    context={
        "model_version": "gpt-4-turbo-v2.3.1",
        "temperature": 0.7,
        "max_tokens": 2000,
        "prompt_template": "discount_evaluation_v3"
    },
    summary="Model configuration used for decision",
    api_key=api_key
)

Record Intermediate Decisions

python
# Record intermediate decision points
add_context(
    decision_id=decision_id,
    context={
        "step": "customer_validation",
        "selected_option": "approve_discount",
        "alternatives_considered": [
            {"option": "reject", "confidence": 0.15},
            {"option": "request_approval", "confidence": 0.20},
            {"option": "approve_discount", "confidence": 0.65}
        ],
        "reasoning": "High confidence in customer reliability"
    },
    summary="Customer validation step completed",
    api_key=api_key
)

Store Confidence Scores

python
# Add confidence scores for different aspects
add_context(
    decision_id=decision_id,
    context={
        "confidence_scores": {
            "customer_verification": 0.98,
            "fraud_detection": 0.92,
            "policy_compliance": 0.95,
            "overall": 0.95
        },
        "risk_factors": {
            "payment_history": "excellent",
            "account_age": "5_years",
            "previous_issues": 0
        }
    },
    summary="Confidence and risk assessment",
    api_key=api_key
)

Complete Workflow with Context

python
# Create decision
decision = create_decision(
    intent="customer.discount.evaluate",
    automation_mode="autonomous",
    api_key=api_key
)
decision_id = decision["decision_id"]

# Add initial context
add_context(
    decision_id=decision_id,
    context={
        "trigger": "customer_request",
        "requested_discount": 0.25,
        "order_value": 10000
    },
    summary="Discount request received",
    api_key=api_key
)

# Read customer data
customer = read_data(
    decision_id=decision_id,
    product="pg_customers_v1",
    purpose="discount_evaluation",
    query={"customer_id": "1001"},
    api_key=api_key
)

# Add analysis context
add_context(
    decision_id=decision_id,
    context={
        "customer_analysis": {
            "tier": customer["records"][0]["tier"],
            "lifetime_value": customer["records"][0]["lifetime_value"],
            "payment_history_score": 0.98
        },
        "recommendation": "approve"
    },
    summary="Customer analysis completed",
    api_key=api_key
)

# Evaluate policy
policy_result = evaluate_policy(
    decision_id=decision_id,
    policy_id="discount_cap_v1",
    inputs={...},
    api_key=api_key
)

# Add final decision context
add_context(
    decision_id=decision_id,
    context={
        "policy_outcome": policy_result["outcome"],
        "final_decision": "approve" if policy_result["outcome"] == "allow" else "request_approval",
        "rationale": policy_result["rationale"]["message"]
    },
    summary="Final decision made",
    api_key=api_key
)

# Close decision
close_decision(decision_id, "commit", api_key=api_key)

Best Practices

  1. Document reasoning: Use context events to document why the agent made specific decisions

  2. Store confidence scores: Include confidence scores and risk assessments to help with auditing

  3. Record model metadata: Store model versions, configurations, and prompt templates for reproducibility

  4. Track intermediate steps: Document key decision points and alternatives considered

  5. Use meaningful summaries: Provide clear, human-readable summaries for each context event

  6. Structure context data: Use consistent structure in context objects for easier analysis

  7. Don't duplicate data: Avoid storing data that's already captured in other events (reads, writes, etc.)

  8. Add context before closing: Add final context events before closing the decision

Use Cases

  1. LLM Reasoning: Store internal reasoning, thought processes, and decision logic from LLM agents

  2. Confidence Scores: Record confidence levels for different aspects of the decision

  3. Model Metadata: Track which model version, configuration, or prompt was used

  4. Intermediate Decisions: Document key decision points and alternatives considered

  5. Risk Assessment: Store risk scores, factors, and assessments

  6. Internal Facts: Record facts or selections made by the agent that don't fit other event types

  7. Design Choices: Document design choices or configuration decisions

  8. Debugging Information: Store debugging information that helps understand agent behavior

Important Notes

  • Append-only: Context events are append-only and cannot be modified after creation

  • Immutable: Once added, context events become part of the permanent decision trace

  • Auditable: All context events are included in decision traces and can be audited

  • No size limit specified: While there's no explicit size limit, keep context reasonable (avoid storing large files or datasets)

  • Must be before close: Context can only be added to open decisions

  • JSON structure: Context must be a valid JSON object (not arrays or primitives at the top level)

Related Methods

TraceMem is trace-native infrastructure for AI agents