Dev.to AI πŸ€– Ai πŸ‘ 0 πŸ“– 7 min read

MoEngage Merlin AI: Multi-Tenant Agent Security on Amazon Bedrock AgentCore

MoEngage built Merlin AI, a set of conversational agents that let marketing and product teams draft campaigns, analyze performance, and adjust targeting from a single chat interface. The system runs on Amazon Bedrock Age

MoEngage built Merlin AI, a set of conversational agents that let marketing and product teams draft campaigns, analyze performance, and adjust targeting from a single chat interface. The system runs on Amazon Bedrock AgentCore and exposes MoEngage's existing platform APIs as MCP tools. The interesting part is not the agent itself. It is how MoEngage enforces tenant isolation when multiple customers share the same tool infrastructure and agent runtime.

The Multi-Tenant Problem

MoEngage is a SaaS platform. Every customer gets their own workspace, campaigns, and user data. When you add agents to a multi-tenant system, you introduce a new attack surface. An agent for Customer A should never see Customer B's campaigns, even if both agents call the same tool to fetch campaign data. The naive approach is to spin up separate agent stacks per tenant. That works, but it duplicates infrastructure and makes tool updates painful.

MoEngage chose a different path: shared agent runtime, shared tool definitions, scoped credentials.

Architecture: Scoped MCP Tools on Bedrock AgentCore

MoEngage converted existing REST APIs into MCP tools. Each tool wraps a platform capability like creating a campaign, fetching analytics, or updating audience segments. The tools themselves are stateless and shared across all tenants. The security boundary lives in the credential scope.

Here is the flow:

  1. User initiates a conversation in the MoEngage UI. The frontend passes a tenant ID and user session token to the agent orchestration layer.
  2. AgentCore receives the request with tenant context. The orchestration layer injects tenant-scoped credentials into the tool execution environment.
  3. Agent selects a tool (for example, fetch_campaign_data). The tool receives the tenant ID as part of the execution context, not as a user-supplied parameter.
  4. Tool calls the MoEngage API with tenant-scoped credentials. The API layer enforces row-level security based on the tenant ID embedded in the credential.
  5. Response flows back through AgentCore to the user. Every tool call is logged with tenant ID, user ID, tool name, and timestamp.

The key insight: tenant ID is not a parameter the agent can manipulate. It is part of the execution context, injected by the orchestration layer before the agent sees the request.

Credential Scoping and Rotation

MoEngage uses short-lived, tenant-scoped API tokens for tool execution. Each token is valid for a single tenant and expires after 15 minutes. The orchestration layer refreshes tokens transparently during long-running conversations.

When a token is revoked (for example, a customer disables API access or a security event triggers a lockdown), the next tool call fails with a 401. The agent sees this as a tool execution error and can either retry or surface the failure to the user. The orchestration layer logs the revocation event and halts further tool calls for that session.

Credential rotation happens at the platform level. When MoEngage rotates API keys, the orchestration layer picks up the new keys from a secrets manager (AWS Secrets Manager in this case) and injects them into new sessions. Existing sessions continue with their current tokens until expiration.

Audit Trail and Observability

Every tool call generates a structured log entry:

{
  "timestamp": "2026-11-16T18:45:12Z",
  "tenant_id": "tenant_abc123",
  "user_id": "user_xyz789",
  "session_id": "session_def456",
  "tool_name": "fetch_campaign_data",
  "tool_input": {"campaign_id": "camp_001"},
  "tool_output_summary": "200 OK, 3 campaigns returned",
  "execution_time_ms": 142,
  "bedrock_request_id": "req_ghi012"
}

These logs feed into CloudWatch and are indexed for security audits. MoEngage can answer questions like "Which agent accessed campaign data for tenant X in the last 24 hours?" or "How many tool calls failed due to credential issues this week?"

The logging layer also tracks cross-tenant access attempts. If an agent somehow tries to pass a different tenant ID as a tool parameter, the tool rejects the call and logs a security event. This has not happened in production yet, but the instrumentation is in place.

Tool Execution Boundaries

Bedrock AgentCore provides the runtime isolation. Each agent session runs in a separate execution context, but all sessions share the same AgentCore instance. The isolation boundary is logical, not physical. MoEngage relies on AgentCore's context management to prevent one session from leaking data into another.

The risk here is a bug in AgentCore's context isolation. If session A's tool output somehow ends up in session B's context, you have a cross-tenant leak. MoEngage mitigates this with end-to-end testing that simulates concurrent sessions from different tenants and checks for data bleed.

They also run a nightly audit job that scans logs for anomalies: tool calls with mismatched tenant IDs, sessions that accessed data from multiple tenants, or tool outputs that contain tenant IDs different from the session's tenant ID.

Failure Modes and Mitigations

Failure Mode Impact Mitigation
Agent hallucinates a tenant ID in tool input Tool rejects call, logs security event Input validation in tool layer, tenant ID injected by orchestration
Credential leak via prompt injection Agent could attempt unauthorized API calls Short-lived tokens, rate limiting, anomaly detection on tool call patterns
AgentCore context bleed Cross-tenant data exposure End-to-end testing, nightly audit scans, AWS support escalation path
Token expiration mid-conversation Tool call fails, conversation stalls Transparent token refresh, retry logic in orchestration layer
Malicious user crafts input to probe other tenants Potential reconnaissance or DoS Input sanitization, rate limiting per tenant, security event logging

The most likely failure is token expiration during a long conversation. MoEngage handles this with automatic refresh, but if the refresh fails (for example, the user's session is revoked), the agent surfaces a clear error message instead of retrying indefinitely.

Deployment Shape

MoEngage runs Merlin AI in a single AWS region (us-east-1) with multi-AZ redundancy. The orchestration layer is a set of Lambda functions behind API Gateway. Each Lambda invocation corresponds to one turn in the conversation. State (conversation history, tenant context, active tool calls) lives in DynamoDB with tenant ID as the partition key.

Bedrock AgentCore is a managed service, so MoEngage does not manage the agent runtime directly. They configure agent definitions (system prompts, tool schemas, model selection) via the Bedrock API and let AWS handle scaling and availability.

Tool definitions are versioned in a Git repo. When MoEngage updates a tool schema or adds a new capability, they deploy a new version of the Lambda layer that contains the tool code. The orchestration layer picks up the new version on the next invocation. There is no downtime, but there is a brief period where some sessions use the old tool version and others use the new one.

Code: Tenant Context Injection

Here is a simplified example of how the orchestration layer injects tenant context into tool execution:

import boto3
import json
from datetime import datetime, timedelta

bedrock_agent = boto3.client('bedrock-agent-runtime')
secrets_manager = boto3.client('secretsmanager')

def invoke_agent_with_tenant_context(tenant_id, user_id, user_input):
    # Fetch tenant-scoped API token from secrets manager
    secret_name = f"moengage/tenant/{tenant_id}/api_token"
    token_response = secrets_manager.get_secret_value(SecretId=secret_name)
    api_token = json.loads(token_response['SecretString'])['token']

    # Build session context with tenant ID and credentials
    session_context = {
        'tenant_id': tenant_id,
        'user_id': user_id,
        'api_token': api_token,
        'token_expires_at': (datetime.utcnow() + timedelta(minutes=15)).isoformat()
    }

    # Invoke Bedrock agent with injected context
    response = bedrock_agent.invoke_agent(
        agentId='merlin-ai-agent',
        agentAliasId='prod',
        sessionId=f"{tenant_id}:{user_id}:{datetime.utcnow().timestamp()}",
        inputText=user_input,
        sessionState={
            'sessionAttributes': session_context
        }
    )

    return response

The tool code reads session_context['tenant_id'] and session_context['api_token'] from the session state. It never trusts tenant ID from user input.

When Cross-Tenant Access Attempts Happen

MoEngage has not seen a successful cross-tenant access in production, but they have logged attempts. Most are benign: a user types a campaign ID from a different tenant (maybe they copied it from a demo account), and the tool rejects the call because the campaign does not exist in the current tenant's scope.

A few attempts looked more suspicious: repeated tool calls with campaign IDs that follow a sequential pattern, suggesting someone was probing for valid IDs across tenants. These triggered rate limiting and a security review. The user turned out to be a legitimate customer testing their own integration, but the pattern matched reconnaissance behavior.

Technical Verdict

Use this approach when you are building a multi-tenant SaaS platform with agents and you need to share tool infrastructure across tenants. The scoped credential pattern works well if your existing APIs already enforce tenant isolation at the data layer. You get the operational benefits of shared infrastructure without duplicating agent stacks.

Avoid this if your platform does not have strong tenant isolation at the API level. If your APIs rely on application-layer checks instead of database-level row security, an agent bug or prompt injection could bypass those checks. In that case, separate agent stacks per tenant are safer, even if they cost more to operate.

Also avoid this if you cannot tolerate the risk of AgentCore context bleed. The isolation boundary is managed by AWS, not by you. If you need physical separation between tenant workloads, run separate Bedrock agent instances or use a different orchestration layer with stronger isolation guarantees.

Source Links

πŸ“° Read the original article on Dev.to AI

Originally published by Dev.to AI. Aggregated on AIWithGhost for educational purposes β€” full credit and traffic to the original publisher.